How to retrieve xml data from Javascript

J.K.A. picture J.K.A. · May 21, 2012 · Viewed 78.8k times · Source

Possible Duplicate:
how to extract values from an XML document using Javascript

My demo.xml file contain the following data:

<?xml version="1.0"?>
<user>
<details>
<name>abc</name>
<class>xyz</class>
<city>pqr</city>
</details>
<info>
<id>123</id>
<code>456</code>
</info>
</user>

I want to fetch all these data from file demo.xml into my code using Javascript. How can I get this? Any solution? Thanks....

Answer

Tom picture Tom · May 21, 2012

here is an example wich can put you in the right direction:

var request = new XMLHttpRequest();
request.open("GET", "/path/demo.xml", false);
request.send();
var xml = request.responseXML;
var users = xml.getElementsByTagName("user");
for(var i = 0; i < users.length; i++) {
    var user = users[i];
    var names = user.getElementsByTagName("name");
    for(var j = 0; j < names.length; j++) {
        alert(names[j].childNodes[0].nodeValue);
    }
}