Home » Posts filed under Parsing XML What and How To

Parsing XML What and How To

Problem:

Parsing XML

I'm currently working on a pretty straight-forward AJAX application. In this application, I get some XML, and then parse it. An example of what I'm working with is as such:
  1. <?xml version="1.0"?>
  2. <postRoot xml:lang="EN">
  3. <post type="comment" date="January 1, 1970">
  4. <user>athlon32</user>
  5. <content>Hello World</content>
  6. </post>
  7. </postRoot>
Now, I've been able to read the XML with XMLHttpRequest , my trouble is with parsing the results. I've tried tons of things, but I just can't seem to get the different child nodes.

Now, let's say we have something like this:
  1. var xml = xhr.responseXML;
  2. var allPosts = xml.getElementsByTagName('post');
Could I use childNode to access user & content ? And if so, how? I've tried many things, but nothing is working :/ Is there a better way to parse the results I get back from the server?

Anyways, thanks in advance. I'm sure this is really simple, but I'm a C coder just trying Javascript for the first time, so I'm kinda lost.

[Re]
Solve:

This should like this
  1. <script type="text/javascript">
  2. if (window.XMLHttpRequest)
  3. xmlhttp=new XMLHttpRequest();
  4. xmlhttp.open("GET","test.xml",false);
  5. xmlhttp.send();
  6. xmlDoc=xmlhttp.responseXML;
  7. myXml = xmlDoc.documentElement.getElementsByTagName("post");
  8. var userValue = myXml[0].getElementsByTagName("user")[0].childNodes[0].nodeValue;
  9. var contentValue = myXml[0].getElementsByTagName("content")[0].childNodes[0].nodeValue;
  10. alert(userValue +","+ contentValue);
  11. </script>
[Re]
Wow Thanks.