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?
Assuming you have an
XMLDocument, the only cross-browser way is to loop through the nodes: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: