The Kat's Work - Blog
Main | Blog | Registration | Login
Sunday
2017-09-24
3:17 AM
Welcome Guest | RSS
Main » 2010 » March » 4 » XML parsing using JQuery.
6:30 PM
XML parsing using JQuery.
I recent problem i had was just how to parse xml returned by ajax.

I know a few of you will scream JSON at me but i have done quite a bit using ajax and xml in the past so there;-).

You can use standard javascript for this(as i have) but as ever jQuery provide tools to do the same functions in just a few lines. When you need to RAD this is very helpful.

So first off lets see how JQuery handles an xmlDocument below.

<root>
<clients>
<client id="1">
<surname>Kat</surname>
<forename>The</forename>
</client>
<client id="2">
<surname>Kat2</surname>
<forename>The</forename>
</client>
</clients>
</root>

The first thing to do is cast the xmlDocument to a jQuery object.

var jXML = $(xml);

Now to select elements we can use the .find() method. 

This really is where jQuery excels. simply put .find(name) will find all element(s) named name.

var clients = $(jXML).find('client');

Notice we can bypass the clients element and go straight to client. We could also just get all surnames in a similar way.

Now to access the properties we either use .attr() method for attributes or the .text() method for text contents.

$(clients).each(function() {
alert($(this).attr('id'));
});

// would give alert 1 and alert 2

$(clients).each(function() {
alert($(this).find('surname').text());
});

// would give alert Kat and alert Kat2

So lets add it all together with the marvellous $.ajax() method.

function retrieveClients(){ $.ajax({ url: "retrieveClients.html", cache: false, type: "GET", dataType: "xml", success: function(xml){
$(xml).find('client').each(function(){
alert($(this).find('forename').text() );

alert($(this).find('surname').text() ); }); } }); };

Views: 859 | Added by: The_Kat | Rating: 0.0/0
Total comments: 0
Name *:
Email *:
Code *:
Login form
Adverts
Search
Calendar
«  March 2010  »
SuMoTuWeThFrSa
 123456
78910111213
14151617181920
21222324252627
28293031
Entries archive
Site friends
  • Create your own site
  • Spree4.com
  • My Blog
  • Statistics

    Total online: 1
    Guests: 1
    Users: 0
    spree4
    Copyright MyCorp © 2017
    Website builderuCoz