简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM