17

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....

3
  • possiblity duplicate : stackoverflow.com/q/5415452/668970 Commented May 21, 2012 at 11:16
  • Although you can get the values using the standard DOM interface your browser (should) provide, most of the times it's better and safer to use a framework (like jQuery) to select the elements. Are you using any? Commented May 21, 2012 at 11:22
  • @Gerardo Lima: No I am not using jQuery for it. I want to use Javascript for this. Can it possible in Javascript or jQuery is better option? Commented May 21, 2012 at 11:24

1 Answer 1

18

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

var request = new XMLHttpRequest();
request.open("GET", "/path/demo.xml", true);
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);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

XMLHttpRequests aren't always asynchrone; the false in request.open("GET", "/path/demo.xml", false) makes it synchrone
It returning the object instead of value
It's working well in Firefox for me,.. but throwing error Javascript runtime error: Access is denied in Chrome & IE
Please don't do this. You're making a synchronous request that will block the main thread. In fact, this pattern is now deprecated: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/…
I edited my post and changed it to asynchrone...ayke is right...in most cases it's not recommended...I don't know if it is even still possible to do this synchrone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.