如何通过其中一个属性查找XML元素,并检索其他属性的值?

时间:2013-04-04 18:15:21

标签: javascript jquery xml-parsing

例如,我在XML文件中有以下内容:

<decisionPoint fileName="5">
<choice label="ARIN, RIPE, APNIC" goTo="5aa"/>
<choice label="Whois.org, Network Solutions" goTo="5aa"/>
<choice label="Google, Bing, Yahoo" goTo="5c"/>
</decisionPoint>

我的值为fileName=5,我的label值为Whois.org, Network Solutions,我需要在goTo上检索<choice>的值有标签价值。我怎么能用jquery来做这个呢?

我是否需要创建整个xml文件的数组?如果是这样,之后是什么?我理解通过它的名字找到一个元素,但是我不知道找到具有X属性的元素的方向,然后检索Y属性的值。

1 个答案:

答案 0 :(得分:2)

jQuery允许您发出查询以在解析的XML片段中进行搜索:

var xml = '<decisionPoint fileName="5">\
<choice label="ARIN, RIPE, APNIC" goTo="5aa"/>\
<choice label="Whois.org, Network Solutions" goTo="5aa"/>\
<choice label="Google, Bing, Yahoo" goTo="5c"/>\
</decisionPoint>';
var $xml = $(xml);

然后

var gt = $xml.find('choice[label="Whois.org, Network Solutions"]').attr('goTo');

找到具有确切属性值的元素,并检索goTo的值。

或者通过部分属性找到:

var gt = $xml.find('choice[label*="Whois.org"]').attr('goTo');

Demonstration(打开控制台)

相关问题