Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse XML structure with javascript JQuery

This is the XML File:

<Test>
    <Category>
        <SubCat>
            <Name>Name</Name>
            <Properties>
                <Key>Key</Key>
                <Value>Value</Value>
            </Properties>
        </SubCat>
        <SubCat>
            <Name>Name</Name>
            <SubCat>
                <Name>AnotherName</Name>
                <Properties>
                    <Key>Key</Key>
                    <Value>Value</Value>
                </Properties>
            </SubCat>
        </SubCat>
    </Category>
</Test>

I would like to get the Name. But only the Name of the first SubCat. And the properties key value. The problem is the SubCat exist two times.

I tried this:

$(xml).find('SubCat').each(function() {
    var name = $(this).find("Name").text();
    alert(name);

}

but this show the name of the first and the second SubCat.

i search for something like this.

rootElement(Category).selectallchildren(SubCat).Name for the first SubCat Name
rootElement(Category).selectallchildren(SubCat).(SubCat).Name for the second SubCat Name

And same explicit select for the Key and values

like image 750
PMe Avatar asked Nov 13 '22 20:11

PMe


1 Answers

The trick here is to make use of jQuery's ability to evaluate CSS3 selectors.

SubCat:nth-of-type(1) selects every first occurrence of SubCat with arbitrary parent elements.

So this should work:

$(xml).find("SubCat:nth-of-type(1)").each(function(){
    var name = $(this).find("Name").text(),
        property = { };    //use an object to store the key value tuple
    property[$(this).find("Properties Key").text()] = $(this).find("Properties Value").text();

    console.log(name, property);
});

//Output:
//Name Object { Key="Value" }
//AnotherName Object { Key="Value"}

Hopefully that's what you want; when writing my first answer I obviously misinterpreted your question, sorry for the confusion...

like image 192
Aletheios Avatar answered Jan 04 '23 02:01

Aletheios