Jon Williams
Jon Williams

Reputation: 59

Access an XML node by value

Is it possible to access an XML section / node using an attribute value (e.g. id) using JavaScript?

For example:

<people>
    <person id='1'>
        <name>Tom</name>
        <age>30</age>
    </person>
    <person id='2'>
        <name>Ian</name>
        <age>22</age>
    </person>
    <person id='3'>
        <name>Ben</name>
        <age>45</age>
    </person>
</people>

I want to be able to select a person with a given id. For example, finding the ID 2 would return Ian.

This is possible in ActionScript like so:

xml.people.person.(@id == 2).name

Is something similar available in JS?

Upvotes: 0

Views: 221

Answers (2)

nemo
nemo

Reputation: 1685

var xml_text="<people><person id='1'><name>Tom</name><age>30</age></person><person id='2'><name>Ian</name><age>22</age></person><person id='3'><name>Ben</name><age>45</age></person></people>";

var xmlParser = new DOMParser().parseFromString(xml_text, "text/xml").documentElement;

var person2Name = xmlParser.querySelector("people person[id='2'] name").textContent ​​;

querySelector takes as input a string, which acts as a css selector on the node.

textContent gets the text of a node.

IE8 doesnt support DOMParser: but you can use the following workaround

  xmlParser =new ActiveXObject("Microsoft.XMLDOM");
  xmlParser.async=false;
  xmlParser.loadXML(xml_text); 

Upvotes: 1

Ry-
Ry-

Reputation: 225203

Assuming you have an XMLDocument, the only cross-browser way is to loop through the nodes:

var people = doc.getElementsByTagName('person');

for(var i = 0; i < people.length; i++) {
    if(people[i].getAttribute('id') === '2') {
        // Found it!
    }
}

If you need to do very complicated expressions, however, it may be worth it to use XPath, even though it needs a bit of cross-browser checking.

Here's the standard way:

document.evaluate('//person[@id='2']/text()[0]', doc.documentElement, null, XPathResult.STRING_TYPE, null).stringValue;

Upvotes: 1

Related Questions