PMe*_*PMe 5 javascript xml jquery xml-parsing
这是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>
Run Code Online (Sandbox Code Playgroud)
我想得到这个名字.但只有第一个SubCat的名称.和属性键值.问题是SubCat存在两次.
我试过这个:
$(xml).find('SubCat').each(function() {
var name = $(this).find("Name").text();
alert(name);
}
Run Code Online (Sandbox Code Playgroud)
但这显示了第一个和第二个SubCat的名称.
我搜索这样的东西.
rootElement(Category).selectallchildren(SubCat).Name for the first SubCat Name
rootElement(Category).selectallchildren(SubCat).(SubCat).Name for the second SubCat Name
Run Code Online (Sandbox Code Playgroud)
并且明确选择Key和值
这里的技巧是利用 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"}
Run Code Online (Sandbox Code Playgroud)
希望这就是您想要的;在写我的第一个答案时,我显然误解了你的问题,对于造成的混乱感到抱歉......
| 归档时间: |
|
| 查看次数: |
2530 次 |
| 最近记录: |