jQuery help - Parse XML into array

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.

Answers


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..

Need Your Help

When using Knockout's foreach binding, do events automatically get cleaned when the view model is updated?

javascript events data-binding knockout.js resource-cleanup

When you write out a section of the DOM using Knockout's foreach binding, and you have events in there (say, using the click binding for example), does Knockout automatically perform cleanup on tho...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.