views:

422

answers:

1

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  A: 

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
}
Ben Blank
Would the xpath work with a soap xml document?
thirsty93
I'm not well-versed in SOAP, but as long as you have a DOM Document object containing your XML, it should work (I've edited the code to make this a little clearer).
Ben Blank
+1 for the xpath solution.
elo80ka