How to parse an xml ajax reply with jQuery?

451 views Asked by At

Using an ajax POST request in jQuery, I get the following xml back from the server:

<?xml version="1.0"?>
<data>

  <subject>
    <val1>...</val1>
    <val2>...</val2>
    <val3>...</val3>
  </subject>

  <subject>
    <val1>...</val1>
    <val2>...</val2>
    <val3>...</val3>
  </subject>

  ... 

</data>

The xml will have an arbitrary number of <subject> tags. How do I loop through each of the subject tags, grabbing the data in val1..val3 for the corresponding tag in each iteration? Thanks.

3

There are 3 answers

2
Crescent Fresh On BEST ANSWER

Make sure your server response sends a "Content-Type" header of "text/xml". Then the response will be the parsed xml document. Your success handler has only to then iterate the resulting DOM:

$.post(url, postData, function(xmlDoc) {
    $('subject', xmlDoc).each(function() {
        var val1 = $('val1', this).text();
        var val2 = $('val2', this).text();
        var val3 = $('val3', this).text();
    })
});
0
Marius On

Using DOM methods:

var subjects = xml.getElementsByTagName("subject");
for(i in subjects){
  alert(subjects[i].getElementByTagName("val1").textContent;
  alert(subjects[i].getElementByTagName("val2").textContent;
  alert(subjects[i].getElementByTagName("val3").textContent;
}
0
Chris Missal On

I can't find the syntax right now, but you can query the object using selectors just like you do html, something like:

$.get('your/url', function(response) {
  $(response).contents("subject"); // just like it's HTML
});