基本上,我有一个xml文档,而我对该文档唯一了解的是属性名称。

有了这些信息,我必须找出该属性名称是否存在,如果确实存在,我需要知道属性值。

例如:

<xmlroot>
  <ping zipcode="94588" appincome = "1750" ssn="987654321" sourceid="XX9999" sourcepw="ioalot">
  <status statuscode="Success" statusdescription="" sessionid="1234" price="12.50">
  </status>
</ping>
</xmlroot>


我有名字appincome和sourceid。有什么价值?

另外,如果文档中有两个Appincome属性名称,我也需要知道,但是我不需要它们的值,仅存在一个匹配项即可。

最佳答案

正则表达式可能不是最好的工具,尤其是当您的JS在具有XPath支持的相当现代的浏览器中运行时。这个正则表达式应该可以使用,但是如果您对文档的内容没有严格的控制,请当心误报:

var match, rx = /\b(appincome|sourceid)\s*=\s*"([^"]*)"/g;

while (match = rx.exec(xml)) {
    // match[1] is the name
    // match[2] is the value

    // this loop executes once for each instance of each attribute
}


另外,请尝试以下XPath,它不会产生误报:

var node, nodes = xmldoc.evaluate("//@appincome|//@sourceid", xmldoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

while (node = nodes.iterateNext()) {
    // node.nodeName is the name
    // node.nodeValue is the value

    // this loop executes once for each instance of each attribute
}

10-07 13:09
查看更多