Versatile xml attribute regex with javascript

怎甘沉沦 提交于 2019-12-23 04:42:32

问题


Basically I have an xml document and the only thing I know about the document is an attribute name.

Given that information, I have to find out if that attribute name exists, and if it does exist I need to know the attribute value.

for example:

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

I have the names appincome and sourceid. what are the values?

Also if there are two appincome attribute names in the document I need to know that too, but I don't need their values, just that more then one match exists.


回答1:


Regular expressions may not be the best tool for this, particularly if your JS is running in reasonably modern browsers with XPath support. This regex should work, but beware of false positives if you don't have tight control over the document's contents:

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
}

Alternatively, try this XPath, which won't generate false positives:

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
}


来源:https://stackoverflow.com/questions/707391/versatile-xml-attribute-regex-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!