Reputation: 889
I am currently developing a HTML game whereby a user drags items and drops them into their correct categories. The categories and their items are defined in an XML document.
My XML format:
<config>
<game>
<title>Dementia</title>
<cat>
<catTitle>Mild</catTitle>
<item>mild-1</item>
<item>mild-2</item>
<item>mild-3</item>
</cat>
<cat>
<catTitle>Moderate</catTitle>
<item>Moderate-1</item>
<item>Moderate-2</item>
<item>Moderate-3</item>
</cat>
<cat>
<catTitle>Severe</catTitle>
<item>Severe-1</item>
<item>Severe-2</item>
</cat>
</game>
I want to parse this XML file using jQuery into seperate arrays based on their category.
So for example:
array1 = [mild-1,mild-2,mild-3]
array2 = [Moderate-1,Moderate-2,Moderate-3] etc...
This would allow me to check if the dropped item's attribute is correct based on the category array.
If you have any other ideas of how this could be done please do suggest.
Thank you in advance.
Upvotes: 1
Views: 8790
Reputation: 31
$($.parseXML(xml)).find("cat").each(function (idx, v) {
arr[idx] = [];
$(v).find("item").each(function (i, vi) {
arr[idx].push($(vi).text()
);
});
because $(xml)
does not work in IE (see this jQuery.find()
doesn't return data in IE but does in Firefox and Chrome).
Upvotes: 1
Reputation: 100175
Try, something like this:
$(document).ready(function() {
var arr = [];
$(xml).find("cat").each(function(idx, v) {
arr[idx] = [];
$(v).find("item").each(function( i , vi) {
arr[idx].push( $(vi).text() );
});
});
console.log( arr );
});
Will return response like:
[
["mild-1", "mild-2", "mild-3"]
,
["Moderate-1", "Moderate-2", "Moderate-3"]
,
["Severe-1", "Severe-2"]
]
So you can access individual array as,
console.log( arr[0] ); //for first, and so on..
Upvotes: 5
Reputation: 944
try like this:
$("cat", xml).each(function () {
$("item", this).toArray();
});
Upvotes: 3