【问题标题】:How can I find an XML element by one of its attributes, and retrieve the value of its other attribute?如何通过其中一个属性找到 XML 元素,并检索其另一个属性的值?
【发布时间】:2013-03-26 23:13:45
【问题描述】:

例如,我在一个 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,我有labelWhois.org, Network Solutions,我需要在具有该标签值的&lt;choice&gt; 上检索goTo 的值。我该如何使用 jquery 来做这件事?

我需要制作整个 xml 文件的数组吗?如果是这样,那之后呢?我了解通过名称查找元素,但我不确定要找到具有 X 属性的元素,然后检索 Y 属性的值。

【问题讨论】:

    标签: javascript jquery xml-parsing


    【解决方案1】:

    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(打开控制台)

    【讨论】:

      猜你喜欢
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 2012-04-05
      • 2014-12-27
      • 2013-11-05
      • 2018-07-28
      相关资源
      最近更新 更多