这是 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>
我想得到名字。但只有第一个 SubCat 的名称。 和属性键值。问题是 SubCat 存在两次。
我试过这个:
$(xml).find('SubCat').each(function() {
var name = $(this).find("Name").text();
alert(name);
}
但这显示了第一个和第二个 SubCat 的名称。
我正在寻找这样的东西。
rootElement(Category).selectallchildren(SubCat).Name for the first SubCat Name
rootElement(Category).selectallchildren(SubCat).(SubCat).Name for the second SubCat Name
同样显式选择键和值
最佳答案
这里的技巧是利用 jQuery 的能力来评估 CSS3 选择器。
SubCat:nth-of-type(1)
选择每个第一次出现的具有任意父元素的 SubCat
。
所以这应该可行:
$(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"}
希望这就是您想要的;在写我的第一个答案时,我显然误解了你的问题,很抱歉造成混淆......
关于javascript - 如何使用 javascript JQuery 解析 XML 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949174/