如何使用javascript JQuery解析XML结构

时间:2022-03-20 14:31:04

This is the XML File:

这是XML文件:

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

我想得到这个名字。但只有第一个SubCat的名称。和属性键值。问题是SubCat存在两次。

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.

但这显示了第一个和第二个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

并且明确选择Key和值

1 个解决方案

#1


1  

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

这里的技巧是利用jQuery评估CSS3选择器的能力。

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

SubCat:nth-​​of-type(1)选择具有任意父元素的每个第一次出现的SubCat。

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

希望这就是你想要的;在写我的第一个答案时,我显然误解了你的问题,抱歉这个混乱......

#1


1  

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

这里的技巧是利用jQuery评估CSS3选择器的能力。

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

SubCat:nth-​​of-type(1)选择具有任意父元素的每个第一次出现的SubCat。

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

希望这就是你想要的;在写我的第一个答案时,我显然误解了你的问题,抱歉这个混乱......