问题
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