XML Parsing with jQuery

Skill

XML Parsing with jQuery

Posted in:

XML is an important part of AJAX. Heck, it's right in the name, "Asynchronous JavaScript and XML", so knowing how to parse XML is equally important. This tutorial will demonstrate how to parse XML using jQuery that should cover almost all cases you'd typically run into.

Using jQuery to parse XML is vaguely reminiscent of LINQ in the recent .NET frameworks. That's a good thing, since LINQ made parsing XML in .NET vastly easier than previous techniques. With jQuery, when you receive XML from a callback, you're not actually getting raw text, you're actually getting a DOM (document object model) that jQuery can traverse very quickly and efficiently to give you the data you need.

Let's start by looking at the example XML document we'll be parsing today. I made a file that contains most things you'd see in a typical XML document - attributes, nested tags, and collections.

<?xml version="1.0" encoding="utf-8" ?>
<RecentTutorials>
  <Tutorial author="The Reddest">
    <Title>Silverlight and the Netflix API</Title>
    <Categories>
      <Category>Tutorials</Category>
      <Category>Silverlight 2.0</Category>
      <Category>Silverlight</Category>
      <Category>C#</Category>
      <Category>XAML</Category>
    </Categories>
    <Date>1/13/2009</Date>
  </Tutorial>
  <Tutorial author="The Hairiest">
    <Title>Cake PHP 4 - Saving and Validating Data</Title>
    <Categories>
      <Category>Tutorials</Category>
      <Category>CakePHP</Category>
      <Category>PHP</Category>
    </Categories>
    <Date>1/12/2009</Date>
  </Tutorial>
  <Tutorial author="The Tallest">
    <Title>Silverlight 2 - Using initParams</Title>
    <Categories>
      <Category>Tutorials</Category>
      <Category>Silverlight 2.0</Category>
      <Category>Silverlight</Category>
      <Category>C#</Category>
      <Category>HTML</Category>
    </Categories>
    <Date>1/6/2009</Date>
</Tutorial>
  <Tutorial author="The Fattest">
    <Title>Controlling iTunes with AutoHotkey</Title>
    <Categories>
      <Category>Tutorials</Category>
      <Category>AutoHotkey</Category>
    </Categories>
    <Date>12/12/2008</Date>
  </Tutorial>
</RecentTutorials>

The first thing you're going to have to do is write some jQuery to request the XML document. This is a very simple AJAX request for the file.

$(document).ready(function()
{
  $.ajax({
    type: "GET",
    url: "jquery_xml.xml",
    dataType: "xml",
    success: parseXml
  });
});

Now that that's out of the way, we can start parsing the XML. As you can see, when the request succeeds, the function parseXML is called. That's where I'm going to put my code. Let's start by finding the author of each tutorial, which are stored as attributes on the Tutorial tag.

function parseXml(xml)
{
  //find every Tutorial and print the author
  $(xml).find("Tutorial").each(function()
  {
    $("#output").append($(this).attr("author") + "<br />");
  });

  // Output:
  // The Reddest
  // The Hairiest
  // The Tallest
  // The Fattest
}

The quickest way to parse an XML document is to make use of jQuery's powerful selector system, so the first thing I do is call find to get a collection of every Tutorial element. Then I call each, which executes the supplied function on every element. Inside the function body, this now points to a Tutorial element. To get an attribute's value, I simply call attr and pass it the name of what attribute I want. In this example, I have a simple HTML span object with an id of "output". I call append on this element to populate it with data. You would probably do something a little more exciting, but I just wanted a simple way to display the results.

See how easy that is? Let's now look at a slightly more complicated one. Here I want to print the publish date of each tutorial followed by the title.

//print the date followed by the title of each tutorial
$(xml).find("Tutorial").each(function()
{
  $("#output").append($(this).find("Date").text());
  $("#output").append(": " + $(this).find("Title").text() + "<br />");
});

// Output:
// 1/13/2009: Silverlight and the Netflix API
// 1/12/2009: Cake PHP 4 - Saving and Validating Data
// 1/6/2009: Silverlight 2 - Using initParams
// 12/12/2008: Controlling iTunes with AutoHotkey

This is very similar to the previous example, except now the values are stored inside element text instead of attributes. Again, I want to go through every Tutorial tag, so I first use find and each. Once I'm inside a Tutorial, I need to find the Date, so I use find again. To get the text inside an XML element, simply call text. I repeat the same process again for the Title, and that's it.

We've now parsed every piece of information except the categories that each tutorial belongs to. Here's the code to do that.

//print each tutorial title followed by their categories
$(xml).find("Tutorial").each(function()
{
  $("#output").append($(this).find("Title").text() + "<br />");

  $(this).find("Category").each(function()
  {
    $("#output").append($(this).text() + "<br />");
  });

  $("#output").append("<br />");
});

// Output:
// Silverlight and the Netflix API
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// XAML

// Cake PHP 4 - Saving and Validating Data
// Tutorials
// CakePHP
// PHP

// Silverlight 2 - Using initParams
// Tutorials
// Silverlight 2.0
// Silverlight
// C#
// HTML

// Controlling iTunes with AutoHotkey
// Tutorials
// AutoHotkey

Once again, I get every Tutorial by using find and each. I then get the Title in the same was as the previous example. Since a tutorial can belong to several categories, I call find and each to iterate over each Category element inside a tutorial. Once I'm inside a Category element, I simple print out its contents using the text function.

Being able to parse elements, attributes, and collections should cover almost every form of XML you'd ever see, and making use of jQuery selectors to get the job done makes parsing XML in JavaScript a breeze. That does it for this tutorial. Hopefully we all learned something about jQuery and XML.

tsantos
01/14/2009 - 09:37

Very nice post

reply

Zach
01/16/2009 - 11:23

Be wary of namespaces!

http://www.zachleat.com/web/2008/05/10/selecting-xml-with-javascript/

reply

The Reddest
01/16/2009 - 12:49

Thanks for the warning! Unfortunately, I didn't think about namespaces when I wrote the article. I guess I should have mentioned somewhere that jQuery doesn't directly support them.

reply

johntantalo
01/16/2009 - 13:07

success: function(xml) { parseXml(xml); } should be success: parseXml

reply

The Reddest
01/16/2009 - 13:21

You're definitely right about that. I'll blame that on a copy/paste error. Where I was using this code I had an another function call in that body. I've corrected the post. Thanks for finding it.

reply

khautinh
03/13/2009 - 15:12

can anyone help me to read this xml file please? I just took over from the previous developer.

courses
  <coursetitle> math
    <coursetime> 1:00pm </coursetime>
    <coursetime> 3:00pm </coursetime>
  </coursetitle

 <coursetitle> phisic
    <coursetime> 1:00pm </coursetime>
    <coursetime> 3:00pm </coursetime>
  </coursetitle>
</courses>

It was using javascript to read before. I though that JQuery may do a better job so I do this for my learning curve with JQuery.
Thanks for helps

reply

The Reddest
03/13/2009 - 15:20

Try posting the comment again. use the [xml] language tag.

reply

Anonymous
03/16/2009 - 18:12

can anyone help me to read this xml file please? I just took over from the previous developer.
1. I like to load course into the drop down box1 with the course
2. If user click on the course, it populate the time into drop down box2.

<courses>
 <course>math
   <time>1:00pm</time>
   <time>3:00pm</time>
 </course>
 <course>phisic
   <time>1:00pm</time>
   <time>3:00pm</time>
 </course>
</courses>

It was using javascript to read before. I though that JQuery may do a better job so I do this for my learning curve with JQuery.

Since I resend this question.
Thanks for helps

reply

Sascha
03/30/2009 - 02:32

Restructure your Xml-File like this:

<courses>
 <math>
   <time>1:00pm</time>
 </math>
 <math>
   <time>3:00pm</time>
 </math>
 <phisic>
   <time>1:00pm</time>
 </phisic>
 <phisic>
   <time>3:00pm</time>
 </phisic>
</courses>

You can access the xml tags with the following jQuery code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>XML Parsing With jQuery</title>
    <script src="jquery-1.2.6.js" type="text/javascript"></script>

 
 <script type="text/javascript">
   
    $(document).ready(function()
      {
          <!-- math -->
        $.get('myData.xml', function(d){
        var options="";
        $(d).find('math').each(function(){
                        var $time = $(this);
            var dropdownvalue = $time.find('time').text();
            options += ' <option value="' + dropdownvalue + '">' + dropdownvalue + '</option>\r\n'
        })
                $("#mymath").html(options);
                ;
                });
                <!-- math End -->
                <!-- phisic -->
        $.get('myData.xml', function(d){
        options="";
        $(d).find('phisic').each(function(){
                        var $time = $(this);
            var dropdownvalue = $time.find('time').text();
            options += ' <option value="' + dropdownvalue + '">' + dropdownvalue + '</option>\r\n'
        })
                $("#myphisic").html(options);
                ;
                });
                <!-- phisic End -->
});
    </script>
       

</head>
<body>
                        <select name="mymath" id="mymath">
                        <option value="1">mymath</option>
                        <select name="myphisic" id="myphisic">
                        <option value="1">myphisic</option>
</body>
</html>

reply

Dario
07/06/2009 - 15:28

Don't work with IE :(

reply

robmar427
09/24/2009 - 10:44

i am making a video gallery. i found a flash template that creates xml file.

XML data looks this:

<?xml version="1.0"?>
<content>
    <gallery Name="All Videos">
        <video Thumb="Signs/400thumb.jpg" VideoClip="Signs/400.flv" Title="400" Copy="0:24:41"/>
        <video Thumb="Signs/moneythumb.jpg" VideoClip="Signs/Money.flv" Title="Blood Money" Copy="0:16:45"/>
        <video Thumb="Dag/fdsthumb.jpg" VideoClip="Dag/friends.flv" Title="Friend Under" Copy="0:22:18"/>
        <video Thumb="Dag/rocky.jpg" VideoClip="Dag/Rocking_Throne.flv" Title="Rocking The King's Throne" Copy="0:36:40"/>
    </gallery>

The gallery works. When I click each thumbnails, the FLV runs.

I want to put film description in my markup. How will i do this for every film currently running?

Thank you...

reply

Michael
11/22/2009 - 01:26

I get confused at:

function parseXml(xml)
{
  //find every Tutorial and print the author
  $(xml).find("Tutorial").each(function()

where is the parameter/variable "xml" declared and instantiated with jquery_xml.xml? Does it magically inherit it from the ajax request. Could someone explain this for me?

reply

The Reddest
11/23/2009 - 09:29

the xml variable is passed into the function automatically by jQuery. parseXml is supplied to jQuery as part of the ajax request.

reply

petrus
01/26/2010 - 05:02

Hi, thanks for this tutorial it has been illuminating.

I'v just one problem - it takes about 6-12 seconds to parse.. :( please help, here is my situation:

XML example: (XML is dynamically created)

<?xml version="1.0" encoding="utf-8"?>
<RESPONSE xsi:noNamespaceSchemaLocation="http://192.168.xxx.xx:10000/rest/schemas/contacts_response.xsd">

<PARAMETERS>
<Ret_Data>
<contact url="http://192.168.xxx.xx:10000/rest/contact/1">
  <CNT_ID>1</CNT_ID>
  <CNT_LASTNAME>Marko</CNT_LASTNAME>
  <CNT_FIRSTNAME>Matic</CNT_FIRSTNAME>
  <CNT_ORGANIZATIONNAME>IT Business Soft</CNT_ORGANIZATIONNAME>
  <CNT_TYPE>1</CNT_TYPE>
  <CNT_NAME>Marko Matic</CNT_NAME>
  </contact>

  <contact url="http://192.168.xxx.xx:10000/rest/contact/14044">
   ...
  </contact>
   ...
   ... etc (about 1500 CONTACT elements)
 
   </Ret_Data>
</PARAMETERS>

(there are about 1500 'contact' nodes) -> IS IT POSSIBLE THAT IT'S SLOW BECAUSE EACH WILL ITERATE TROUGH EVERY CHILD - CAN I RESTRICT SOMEHOW SOMETHING?)

 
$(document).ready(function()
{
 $.ajax({                  
   type: "GET",
   url: "http://192.168.xxx.xx:10000/rest/contacts/",
   dataType: "xml",
   success: parseXML,
   error: err    
        });              
});    
function err(xhr, reason, ex)
{
  $('#output').append(reason);
}
function parseXML(xml)
{
$(xml).find("contact").each(function()
{
 $("#content").append($(this).find("CNT_NAME").text());
$("#content").append(": "+
$(this).find("CNT_ORGANIZATIONNAME").text() +" <br />");       
});      
}

<body> 

   <div id="title">
     <h3>Printing: Contact Name followed by organization</h3>
   </div>
       
   <div id="content">
       
   </div>

</body>

BUGS:

1) WORKS IN SAFARI/IE - DOES NOT WORK IN FIREFOX (ParseError - it doesn't even call the ParseXML function, just err)

2) Why so slow?? Why cca 10 seconds?

PLEASE HELP THX

ps.

would it be faster if i used NATIVE DOM METHODS? I really really like jQuery, it's so programmer friendly...

reply

Anonymous
03/12/2010 - 21:23

Any way to parse data from an xml file whose tags are not known before?

I mean is there any way to generalize it to parse any xml doc on the go?

reply

Sam
04/01/2010 - 08:10

Thanks for your help. It helped finnish my project.

I put a link back as resources used in my blog post: http://samosexp.wordpress.com/2010/04/01/using-xml-linq-and-jquery-for-a-google-maps-store-locator/

This is how I used it to read xml with Json, maybe people read this blog who try to achieve the same thing:

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService/StoreService.asmx/GetStoresInfo",
                //data: "{}",
                dataType: "xml",
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#output").append(XMLHttpRequest.responseText + "<br />TextStatus: " + textStatus + "<br />ErrorThrown: " + errorThrown);
                },
                success: function(xml) {
                // hier wordt de xml uitgelezen
                    $(xml).find("store").each(function() {
                        var storename = $(this).find("name").text();
                        var latitude = $(this).find("latitude").text();
                        var longitude = $(this).find("longitude").text();
                        var point = new GLatLng(latitude, longitude);
                        var marker = new GMarker(point);

                        map.addOverlay(marker);


                    });
                    map.setUIToDefault();

                }
            });

reply

Suraj
09/13/2010 - 17:08

I am trying to a simple plain POST with a parameter name and value. But my response is in XML. How do I parse the response, how do I set the data type since my input is plain name value pair. Can I use similar without JSON? I am new the JQurey so I am trying to make is very simple for understanding.

Thank you.

reply

followmollo
04/12/2010 - 09:06

Hi There,

Thanks for the great tutorial, I have the following XML file and wondering how I would go about adding feature to turn off induvidual announcements by adding something like status="on" / status="off"?

<Announcements>
  <Announcement>
        <Date>1/13/2009</Date>
    <Title>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Title>
    <Content>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac augue nec est dapibus interdum. Curabitur convallis quam quis tortor pellentesque sagittis.
    </Content>
  </Announcement>
  <Announcement>
        <Date>1/12/2009</Date>
    <Title>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Title>
    <Content>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac augue nec est dapibus interdum. Curabitur convallis quam quis tortor pellentesque sagittis.
    </Content>
  </Announcement>
  <Announcement>
        <Date>1/6/2009</Date>
    <Title>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Title>
    <Content>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac augue nec est dapibus interdum. Curabitur convallis quam quis tortor pellentesque sagittis.
    </Content>
</Announcement>
  <Announcement>
        <Date>12/12/2008</Date>
    <Title>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Title>
    <Content>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac augue nec est dapibus interdum. Curabitur convallis quam quis tortor pellentesque sagittis.
    </Content>
  </Announcement>
</Announcements>

Thanks!
David

reply

Anonymous
05/12/2010 - 08:10

GREAT, Could solve my problem with this great tutorial.

reply

rico
05/17/2010 - 19:20

im having a problem with the find() function.
For me it works in firefox and chrome perfectly, but any version of explorer returns 'undefinded'

reply

Timothy
06/05/2010 - 09:36

Internet Explorer is annoying as usual about this and you need to make exceptions for it. I was writing a photo gallery plugin that reads from XML and every browser except for IE was working great. Here's what I had to do:

type: 'GET',
                        url: 'photos.xml',
                        dataType: ($.browser.msie) ? "text" : "xml", //if Browser is internet explorer, the datatype is text, otherwise xml.
                        success: getXML,
                        complete:

reply

Timothy
06/05/2010 - 09:37

And then in my "success" function, I had to add this:

if ($.browser.msie) {
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.loadXML(xml);
    xml = xmlDoc;
}

reply

Anonymous
01/04/2011 - 04:41

Thank you Timothy, it worked for me. Thanks a lot....
Happy Coding...

reply

softxml
06/08/2010 - 03:01

SoftXpath - Lightweight cross browser JavaScript library for querying complex XML documents using powerful Xpath expressions.

Demo

reply

James9198
06/11/2010 - 09:20

I have a two xml files.

One contains orders for my store and the other contains order details.

Could I use this jquery scripts to grab the data from one file and the order details from the other file and merge them together?

Example:

xmlfile 1:

 <Orders>
  <orderid>1</orderid>
  <customerid>1</customerid>
  <shipfirstname>John</shipfirstname>
  <shiplastname>Doe</shiplastname>
  <shipaddress1>11111 Where Ever</shipaddress1>
  <shipaddress2 />
  <shipcity>Yep</shipcity>
  <shipstate>MD</shipstate>
  <shippostalcode>111111</shippostalcode>
  <shipphonenumber>111-111-1111</shipphonenumber>
  <shipfaxnumber />
  <total_payment_received>0</total_payment_received>
  </Orders>

xml file 2:

<OrderDetails>
  <orderid>1</orderid>
  <productcode>testRZ</productcode>
  <options />
  </OrderDetails>

I would like to be able the grab all the order details and attach it to the orders.

reply

The Reddest
06/11/2010 - 10:26

I would create two objects to hold the information contained in the two XML files.

function Order()
{
  this.orderid = 0;
  this.customerid = 0;
  ...
  this.orderDetails = null;
}

function OrderDetails()
{
  this.orderid = 0;
  this.productcode = "";
  ...
}

I would then parse the 2nd XML file into a collection of OrderDetail objects. Then I'd parse the 1st XML file. When each Order is parsed, I'd lookup the corresponding OrderDetails object by the orderid and set the property to that object.

reply

zwalex
08/01/2010 - 16:55

The Reddest,
I am only getting [object Object] returned as what should be parsed xml parts (see below). I want to do something very similar like you described in your article - inserting a list of customers from an xml file into my html (as list elements).
I obviously have something wrong somewhere in my code that I am unable to find after staring at it for hours ...
I am running jQuery 1.4.2 on Mac OS X 10.6.4. Same in Safari 5 and Firefox.
Any help appreciated.
alex

<?xml version="1.0" encoding="utf-8"?>
<custList>
<customer type="IB" grade="A" ID="1111">ACME, Inc.</customer>
<customer type="IB" grade="A" ID="2222">Customer LLC</customer>
<customer type="Prospect" grade="A" ID="3333">Prospect, Inc.</customer>
</custList>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
        <head>
                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                <title>Customer List</title>
            <script type="text/javascript" src="lib/jquery/jquery-1.4.2.js"></script>
                <script type="text/javascript" src="customer.js"></script>             
        </head>
        <body>
                <ul id="custList">
                </ul>
                <div id="output"/>
        </body>
</html>

$(document).ready(function(){
        $.ajax({
    type: "GET",
    url: "customer.xml",
    dataType: "xml",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $("#output").append(XMLHttpRequest.responseText + "<br />TextStatus: " + textStatus + "<br />ErrorThrown: " + errorThrown);
        },
    success: function(xml) {
                $(xml).find("customer").each(function()
                        {
                $("#custList").append("<li>" + $(this) + "</li>");
                        });            
                }
        });
});

reply

zwalex
08/01/2010 - 17:21

Oops - posted too early and after staring at it 10 minutes more I found the easy, stupid thing ...
The iteration in the each loop obviously _is_ an object and not [yet ?] a valid [X]HTML snippet that could be inserted as is into the html (although in my case it could ...).

I needed to pick out the attributes [$(this).attr("xxxx")] or the inner text of the element [$(this).text()] to produces results.

I hope that somebody else can profit from that mistake ...
alex

reply

newcircle live in S.Korea
08/03/2010 - 00:18

very nice post.
thank you. bye.

reply

Anonymouschi flat irons
08/06/2010 - 20:45

Really great informative blog post here and I just wanted to comment & thank you for posting this. I've bookmarked youi blog and I'll be back to read more in the future my friend! Also nice colors on the layout, it's really easy on the eyes.

reply

ebrent
08/17/2010 - 09:19

HI. Thanks so much for this article. I've learned a lot. I have one quick question = how can I parse the XML and create a list with a link to a detail page from the same data?

For instance I have a feed where I just want to first display a list with the title but make it a link that will then display all of the detailed desc and info?

thank you !! Any help or pointers would be much appreciated! Ya know, I think that to do the type of manipulation I want, I need to convert the XML to JSON. I'll try that.

cheers, brent

reply

gusgus
08/23/2010 - 13:37

If your xml file has dates for given events (or maybe in your case, dates for live tutorial sessions in your tutorial xml); how would you pull dates from this year (2010) and next (2011), and ones from 'today's date' forward. Also, how would you incorporate it into your jquery request to NOT grab the ones before 'today's date', or after this year (2010).

And how would you differentiate the two years in your xml file as, for instance, you had some tutorial live viewings for tutorials that are a two-day viewing (Sep 10 and 11, 2010 for instance).

reply

Amber
10/27/2010 - 01:09

Hi, I was wondering if anybody knows how to get a JSON response from an xml file using ajax.

reply

RichardF
01/24/2011 - 16:58

This was a huge help, but when I tried to modify it for my situation I come up short. It works perfectly when I appended the output to a div. But I want to set string variables to different languages stored in XML files.

<?xml version="1.0" encoding="utf-8"?>
<Module abbrv="hr101" name="Human Rights 101">
  <sections>
    <section>
      <id>00</id>
      <file>hr101-00-intro</file>
      <label>Welcome</label>
    </section>
    <section>
      <id>A0</id>
      <file>hr101-A0-about</file>
      <label>About Human Rights</label>
    </section>
  </sections>
</Module>

I tried...

function requestXML(path)
{
        var theXML = $.ajax({
    type: "GET",
    url: path,
    dataType: "xml"
        });
        return theXML;
}

(I also tried that with a success function that just said return xml; and got the same result)

I then call it like so...

        var getXML = requestXML( PATH_TO_XML );
        var myModuleName = $(getXML).find('Module').attr('name');
alert('myModuleName='+myModuleName);

The alert says "undefined"

What am I not getting?

reply

RichardF
01/27/2011 - 10:09

I remained unable to solve this until I happened on the article here: http://techmonks.net/getscript-and-firebug-code

I copy/pasted their final example to the top of my .js file and presto--it works.

A fix for $.getScript() :

jQuery.extend({
        getScript: function(url, callback) {
                var head = document.getElementsByTagName("head")[0] || document.documentElement;
                var script = document.createElement("script");
                script.src = url;

                // Handle Script loading
                {
                        var done = false;

                        // Attach handlers for all browsers
                        script.onload = script.onreadystatechange = function() {
                                if ( !done && (!this.readyState || this.readyState === "loaded" ||
                                       this.readyState === "complete") ) {
                                        done = true;
                                        //success();
                                        //complete();
                                        if ( callback)
                                                callback();

                                        // Handle memory leak in IE
                                        script.onload = script.onreadystatechange = null;
                                        if ( head && script.parentNode ) {
                                                head.removeChild( script );
                                        }
                                }
                        };
                }

                head.insertBefore( script, head.firstChild );
                return undefined;
        }
});

reply

RichardF
01/27/2011 - 10:16

Oh yeah, as you might have guessed I abandoned the .XML file entirely and created a JSON Object within a .js file. I set a cookie for the language, or allow the user to set one from a select, then I use that to construct the path to a language-specific .js file, which I now generate from a mySQL database (using ColdFusion).

reply

kiran.j
02/21/2011 - 06:50

<values id='one'>one</values>
<values id='two'>two</values>
<values id='three'>three</values>

can anybody plese tell how to retrieve this xml..
i am using IE8 browser.
I tried

success: function(xml) {
 $(xml).find("values").each(function()
 {
   alert('demo');
 });
}

but its not working.

reply

Anonymous
03/17/2011 - 15:48

Hi,

Here is a cross browser XML parsing / helper library:

http://extremedev.blogspot.com/2011/03/xml-parsing-and-other-xml-utilities.html

--------------------
You can find me on: http://extremedev.blogspot.com

reply

mcometa
03/22/2011 - 20:38

Thank you so much =]

reply

Anonymous
04/15/2011 - 03:32

Hey Hi,

I have an issue with parsing xml while using jquery for the same :
I am loading content into a div tag and then trying to load XML into the html page using jquery. My problem is that it works for the first two link clicks but after that it does not work. I know i need to rebind the whole thing but i am not able to figure out the way of doing it. Here's the code snippet :

$(document).ready(function(){
initBinding();

$.ajax({
  type: "GET",
  url: "../XML/contact.xml",
  dataType: ($.browser.msie) ? "text" : "xml",
  success: parseXML
  });

function parseXML(data) {
  if (typeof data == "string") {
     xml = new ActiveXObject("Microsoft.XMLDOM");
     xml.async = true;
     xml.loadXML(data);
     }
  else {
    xml = data;
    }
  var pos = $(".content:first");
 
  $(xml).find('site').each(function(){                                  
    var desc = $(this).find('desc').text();
    pos.append(desc);                    
  });
  }
});

function initBinding()
{
  var ajaxResponse = $("html");
  // Move your scripts into a new element
  var scripts = ajaxResponse.find('script');  
  var tempScripts = $().append(scripts);
   // Append your content, followed by your script tags
 
  $(document).append(ajaxResponse);
  $(document).append(tempScripts);                      
}

any kinda help is needed :)

reply

Tarik
05/09/2011 - 04:20

Hi All,
I have a requirement.. I have right and left navigation menus and submenus(with links), all these data has to come from the xml using jquery. Organised in Div blocks and we need to just populate the data on these divs.Also there is an attribute (expand) in xml set to either true or false such that we will show/hide div block as default.Below is the snippet

Right navigation should be shown by default and left navigation should be hidden based on the expand value.

Please help me.

Thanks

reply

anonymous
05/20/2011 - 08:42

Hello everybody

Is it possible to store images in the xml-file and display them in the same manner as done with the text?

Thanks

reply

Anonymous
05/31/2011 - 23:36

<schedules type="daily">
        - <schedule>
        - <flights>
        - <flight>
          <carrierInformation>Indigo Airways</carrierInformation>
          <flightNumber>IN401</flightNumber>
        - <flightDetails>
          <link href="/flightinfo/dyn/FlightLogistics?flightquery=QF,401,20110601,SYD,MEL,763" />
          </flightDetails>
          </flight>
          </flights>
        - <route>
          <city>Chennai</city>
          <city>Mumbai</city>
          </route>
          <departs>06:00, Wed 1 Jun 2011</departs>
          <arrives>07:35, Wed 1 Jun 2011</arrives>
          <stops>0</stops>
          </schedule>
        - <schedule>
        - <flights>
        - <flight>
          <carrierInformation>Indigo Airways</carrierInformation>
          <flightNumber>IN405</flightNumber>
        - <flightDetails>
          <link href="/flightinfo/dyn/FlightLogistics?flightquery=QF,405,20110601,SYD,MEL,73H" />
          </flightDetails>
          </flight>
          </flights>
        - <route>
          <city>Chennai</city>
          <city>Mumbai</city>
          </route>
          <departs>06:30, Wed 1 Jun 2011</departs>
          <arrives>08:05, Wed 1 Jun 2011</arrives>
          <stops>0</stops>
          </schedule>
        - <schedule>
        - <flights>
        - <flight>
          <carrierInformation>Indigo Airways</carrierInformation>
          <flightNumber>IN501</flightNumber>
        - <flightDetails>
          <link href="/flightinfo/dyn/FlightLogistics?flightquery=JQ,501,20110601,SYD,MEL,320" />
          </flightDetails>
          </flight>
          </flights>
        - <route>
          <city>Chennai</city>
          <city>Mumbai</city>
          </route>
          <departs>06:40, Wed 1 Jun 2011</departs>
          <arrives>08:10, Wed 1 Jun 2011</arrives>
          <stops>0</stops>
          </schedule>
</schedules>

I want to calculate the time taken for each root by subtracting the arrival tag value with departs tag value. After doing all subtractions I need to find out the trip which has taken least time. Pls post ur ideas

reply

The Reddest
06/01/2011 - 08:45

I'd just grab any javascript library capable of parsing that date format. Datejs is the first one I found using a Google search. Create an object to hold the details for each flight and populate a collection of them as you parse the XML.

To calculate the duration of each flight, populate the built-in javascript date object using the values parsed by the date library. The date object has a function, getTime, which returns the milliseconds since the epoch. Get the milliseconds for the departure time and arrival times and subtract them - this will give you the duration of each flight, in milliseconds.

To find the fastest, iterate over the collection of objects and find the one with the smallest duration in milliseconds.

reply

webdad3
06/17/2011 - 14:04

I'm looking to find out how jQuery can parse an XML document where I don't have the parent and child nodes known to me. I'm wondering if there is something that I could use to get me the parent node names and then the children node names underneath the parent.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.