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.

Want to learn more about jQuery? Check out these great books:

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

silverbuyer
03/13/2012 - 13:18

can you help me out with a project, I want all my forms to be developed in jquery and output xml to be further processed. you can skype me, my userid is silverbuyer. This is for everyone on here that is capable and needs the money! Cheers!

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

Jamie
06/30/2011 - 19:29

This isn't really about Parsing XML as much as traversing xml... Parsing deals with the nuts and bolts of changing the text/xml representation INTO the DOM representation

reply

Arun Raj
07/19/2011 - 05:13

Try this: http://www.arunraj.co.in/index.php?option=com_content&view=article&id=7:populate-table-using-ajax&catid=4:javascript&Itemid=9

reply

MF_Soul
08/29/2011 - 15:04

Hello,
I am trying to parse the XML given below.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <LicenseKey licensedTo="DEMO" xmlns="http://www.abc.com/loginservices">
        - <DefaultQuoteTypes>
                <QuoteType name="A" code="W" />
                <QuoteType name="B" code="X" />
                <QuoteType name="C" code="Y" />
                <QuoteType name="D" code="Z" />
        </DefaultQuoteTypes>
        - <Products>
                - <Product name="Q1" code="U1">
                        - <States>
                                <State name="Arizona" code="AZ" />
                                <State name="California" code="CA" />
                                <State name="Michigan" code="MI" />
                                <State name="Nevada" code="NV" />
                                <State name="New Hampshire" code="NH" />
                                <State name="New Jersey" code="NJ" />
                                - <State name="New York" code="NY">
                                        - <excludedQuoteTypes>
                                                <excludedQuoteType name="C" code="Y" />
                                                <excludedQuoteType name="D" code="Z" />
                                        </excludedQuoteTypes>
                                </State>
                                <State name="Ohio" code="OH" />
                                <State name="Virginia" code="VA" />
                        </States>
                </Product>
                - <Product name="Q2" code="U2">
                        - <States>
                                <State name="Arizona" code="AZ" />
                                <State name="California" code="CA" />
                                <State name="New Jersey" code="NJ" />
                                <State name="Ohio" code="OH" />
                                <State name="Virginia" code="VA" />
                        </States>
                </Product>
        </Products>
</LicenseKey>

I want to display Quote types, states and respective product in drop down menu/Tree structure. Can anyone suggest me way to work this out ??

reply

Anonymous
09/09/2011 - 17:07

How does #output work?

reply

The Reddest
09/12/2011 - 08:30

From the article:
"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."

"#id" is a jQuery selector that finds the HTML object with the specified id. So "#output" will find my HTML span object which I gave the id, "output".

<span id="output" />

reply

HI
09/21/2011 - 01:14

Iam planning to get the imagename using jquery , Ill display one image at a time. If i click on next or prev button i want the details of image names. Please find the sample xml listed below. Thanks in advance.

<?xml version="1.0" encoding="iso-8859-1"?>
 <Pages>
  <Title>1</Title>
  <Title>2</Title>
  <Title>3</Title>
  <Title>4</Title>
  <Title>5</Title>
  <Title>6</Title>
  <Title>7</Title>
 </Page>

reply

curt
12/05/2011 - 17:17

I'm trying to read and parse a XML file from Google Finance API:

http://www.google.com/ig/api?stock=.ftse

<xml_api_reply version="1">
<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<symbol data=".FTSE"/>
<pretty_symbol data=".FTSE"/>
<symbol_lookup_url data="/finance?client=ig&q=.FTSE"/>
<company data="FTSE 100"/>
<exchange data="INDEXFTSE"/>
<exchange_timezone data=""/>
<exchange_utc_offset data=""/>
<exchange_closing data=""/>
<divisor data="2"/>
<currency data="GBP"/>
<last data="5567.96"/>
<high data="5602.80"/>
<low data="5545.93"/>
<volume data="0"/>
<avg_volume data=""/>
<market_cap data=""/>
<open data="5552.44"/>
<y_close data="5552.29"/>
<change data="+15.67"/>
<perc_change data="0.28"/>
<delay data="15"/>
<trade_timestamp data="4 hours ago"/>
<trade_date_utc data="20111205"/>
<trade_time_utc data="163530"/>
<current_date_utc data="20111205"/>
<current_time_utc data="212935"/>
<symbol_url data="/finance?client=ig&q=.FTSE"/>
<chart_url data="/finance/chart?q=INDEXFTSE:.FTSE&tlf=12"/>
<disclaimer_url data="/help/stock_disclaimer.html"/>
<ecn_url data=""/>
<isld_last data=""/>
<isld_trade_date_utc data=""/>
<isld_trade_time_utc data=""/>
<brut_last data=""/>
<brut_trade_date_utc data=""/>
<brut_trade_time_utc data=""/>
<daylight_savings data="false"/>
</finance>
</xml_api_reply>

I have this Javascript:

<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
                               
        $(document).ready(function()
                {
                  $.ajax({
                        type: "GET",
                        url: "http://www.google.com/ig/api?stock=.ftse",
                        dataType: "xml",
                        success: parseXml,
                        //error: err
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#output").append(XMLHttpRequest.responseText + "<br />TextStatus: " + textStatus + "<br />ErrorThrown: " + errorThrown);
                        }
                  });
                  /* document.write("loaded XML file"); */
                });
               
        function err(xhr, reason, ex)
                {
                  $('#output').append(reason);
                }
               
        function parseXml(xml)
                {
                  //find every last and print the value
                  $(xml).find("last").each(function()
                          {
                                $("#output").append($(this).attr("data") + "<br />");
                          });
                  document.write("executed parseXML");
               
                }
</script>

However, I get an error:

TextStatus: error
ErrorThrown:

Can anybody help solve the problem?

reply

The Reddest
12/05/2011 - 17:39

What does your browser's error console say? My guess is that this is a cross-domain issue. Most of the time javascript cannot make callbacks to a domain that is different than the one hosting the javascript.

reply

curt
12/05/2011 - 19:09

Am I correct to assume that you are replying to my posting?

How do I view my browser's error console? (I'm using Google Chrome)

You wrote: "My guess is that this is a cross-domain issue. Most of the time javascript cannot make callbacks to a domain that is different than the one hosting the javascript."

Where in my code is it making a callback? I'm not sure I understand what you mean. Are you referring to the line that has the URL to the web service providing the XML file?

$.ajax({
                        type: "GET",
                        url: "http://www.google.com/ig/api?stock=.ftse",
                        dataType: "xml",
                        success: parseXml,
                        //error: err
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#output").append(XMLHttpRequest.responseText + "<br />TextStatus: " + textStatus + "<br />ErrorThrown: " + errorThrown);
                        }
                  });

I have the Javascript file (jquery.js) residing on the same webserver as the index.html file.

reply

The Reddest
12/06/2011 - 09:14

In Chrome, the console is located here: Settings (wrench icon) -> Tools -> JavaScript console

What I mean by cross-domain is that your website (let's say example.com) is not at the same domain as the the one being requested (google.com). That $.ajax call is telling the browser to go download some information from google.com, and since your site is on example.com, this is a security violation.

reply

curt
12/06/2011 - 11:25

Thanks for your help!

I found the console and it had this message:

"XMLHttpRequest cannot load http://www.google.com/ig/api?stock=.ftse. Origin http://vomad.com is not allowed by Access-Control-Allow-Origin."

What's interesting is that I changed the URL from:

http://www.google.com/ig/api?stock=.ftse

to

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&env=store://datatables.org/alltableswithkeys

and I no longer get the XMLHttpRequest message anymore.

Would you know why this happens with Google's URL but not Yahoo's URL?

FYI, I had changed this

success: parseXml,

to this

success: parseXml(xml),

and I no longer get the previous error message. I get this:

executed parseXML

which means that the parseXml function is getting executed at least, which it wasn't before.

reply

The Reddest
12/06/2011 - 11:38

There are mechanisms that will allow cross-domain requests to be made. These are typically on the server-side. Yahoo allows cross domain requests to be made and Google does not.

We've used Yahoo Pipes for a couple of tutorials here to act as a proxy to APIs that do not allow cross domain access.

reply

curt
12/07/2011 - 23:22

That seems weird that if you enter this URL:

http://www.google.com/ig/api?stock=.ftse

into your browser, it works fine and shows you the XML data.

But, if you use that URL in Javascript, then you get the cross-domain issue. Do you know why? In both scenarios, it's the client's machine that is trying to access Google.

reply

The Reddest
12/08/2011 - 09:46

If you enter the URL in the address bar, you are directly instructing the browser to request that resource - just like any other website. When javascript is doing it, the user visiting the site has no control over what is being requested. This is, more often than not, an annoying security restriction, but there are legitimate reasons why it exists.

Here's a Wikipedia article on the same origin policy, but there are tons of other articles out there as well.

reply

Anonymous
12/29/2011 - 08:06

Hi, I am reading your tutorial but I cannot get my code to work is there something wrong you can spot? Please help me:

<shops>
<shop shopname="shop1" cat="shop"/>
</shops>

function remoteXML() {
      $(document).ready(function() {
          $.ajax({
              type : "GET",
              url : "http://www.myx.com/list.xml",
              dataType : "xml",
              success : parseXml,
              error : err
          });
      });
  }
  function parseXml(xml) {
      //find every Tutorial and print the author
      $(xml).find("shop").each(
              function() {
                  $("#directory").append(
                          "<li><a href=\"#\">" + $(this).attr("shopname")
                                  + "</a></li>");
              });
  }

reply

Anonymous
12/29/2011 - 08:14

I feel so stupid, the code is good. I parse the wrong xml file. Please ignore my post above :(

reply

Anonymous
01/24/2012 - 17:34

Can someone please help me. I am basically trying to build a table from XML to HTML, dynamically with jQuery. Nothing is showing up. I am new at this. This is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<menu>
        <group>        
                        <desc>Full Breakfast (includes toast, home fries, coffee or juice</desc>
                        <size>One Size</size>
                        <item>
                                <name>2 large eggs any style w/choice of bacon, sausage or ham</name>
                                <price>$ 5.75</price>                  
                        </item>
        </group>
        <group>
                        <desc>Omelets (All made with 3 large eggs includes toast, home fries, coffee or juice)</desc>
                        <size>One Size</size>
                        <item>
                                <name>Cheese</name>
                                <price>$ 5.60</price>
                        </item>
                        <item>  
                                <name>Smoked Virginia Baked ham and cheese</name>
                                <price>$ 5.90</price>
                        </item>
                        <item>
                                <name>Cured smoked bacon and cheese</name>
                                <price>$ 5.90</price>
                        </item>
                        <item>
                                <name>Sausage and Cheese</name>
                                <price>$ 5.90</price>
                        </item>
                        <item>
                                <name>Egg white w/5 vegetable fillings</name>
                                <price>$ 6.70</price>
                        </item>
                        <item>
                                <name>Western (ham, peppers and onions)</name>
                                <price>$ 6.10</price>
                        </item>
                        <item>
                                <name>Veggie with Cheese</name>
                                <price>$ 6.40</price>
                        </item>
                        <item>
                                <name>Spinach and Feta</name>
                                <price>$ 5.95</price>
                        </item>
        </group>
</menu>

This is my Javascrip:
[javascrip]

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

function parseXml(xml){

// Build an HTML string
myHTMLOutput = '';
myHTMLOutput += '';
$(xml).find("group").each(function() {

var groupDesc = $(this).find("desc").text();
var groupSize = $(this).find("size").text();

myHTMLOutput += ''+groupDesc+''+groupSize+'';

// Run the function for each student tag in the XML file
$(this).find("item").each(function() {
var groupName = $(this).find("name").text();
var groupPrice = $(this).find("price").text();

// Build row HTML data and store in string
myHTMLOutput += ''+groupDesc+''+groupSize+'';
}); /* End Item */

}); /* End Group */
myHTMLOutput += '';
// Update the DIV called Content Area with the HTML string
$("#mainContent").append(myHTMLOutput);

}); /* Function */

[/javascript]

what am i doing wrong?

reply

Anonymous
01/24/2012 - 17:40

Sorry the javascript file didnt come out right. Let me try again>

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

       
function parseXml(xml){
       
                               
                // Build an HTML string
                myHTMLOutput = '';
                myHTMLOutput += '<table class="persist-area">';
                     $(xml).find("group").each(function() {
                                                 
                                var groupDesc = $(this).find("desc").text();   
                                var groupSize = $(this).find("size").text();
                                   
                myHTMLOutput += '<tr><th>'+groupDesc+'</th><th>'+groupSize+'</th></tr>';
               
               
                $(this).find("item").each(function() {
                        var groupName = $(this).find("name").text();
                        var groupPrice = $(this).find("price").text();
                                       
                        // Build row HTML data and store in string
                        myHTMLOutput += '<tr><td>'+groupDesc+'</td><td>'+groupSize+'</td></tr>';
                }); /* End Item */
                               
               
        }); /* End Group */
                         myHTMLOutput += '</table>';
                         // Update the DIV called Content Area with the HTML string
              $("#mainContent").append(myHTMLOutput);
                         
  }); /* Function */   
         

reply

The Reddest
01/24/2012 - 22:59

Does the Javascript error console say anything?

reply

Anonymous
01/24/2012 - 23:54

Yes it says:
'Uncaught SyntaxError: Unexpected token )'
Is there some kind of a syntax error in the HTML code?

reply

Anonymous
01/25/2012 - 00:09

I should mention that there are other javascript functions in the html page. When I take the above mentioned javascript out of the html page, javascript error cosole doesnt reflect any errors. But when I put it back in, it says that there is a syntax error(i.e. see below) So it appears that there is some kind of a syntax error in the javascript. I cant seem to pinpoint it. Sorry Im really new at this. Any help would be appreciated.

reply

Anonymous
01/25/2012 - 08:18

I ran it in firefox and in firebug script tab that part of code doesnt even appear. I should also say that the alert statement doesnt work in that part of code. Its a mystery. Do you have any ideas.

reply

Anonymous
01/25/2012 - 09:18

I have tried modifying the javascript a little bit. And the error in chrome says this: XMLHttpRequest cannot load file:///C:/Documents%20and%20Settings/Administrator.LENOVO-12FB69B1/Desktop/ThinkCreative/SeasidePizza/MagicLine/Header/fullmenu2.xml. Origin null is not allowed by Access-Control-Allow-Origin.
And this is the modified code:

$(document).ready(function(){
       
               
        if ($.browser.msie) {
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.loadXML(xml);
    xml = xmlDoc;
}  
       $.get('fullmenu2.xml', function(xml){

                       
                // Build an HTML string
                myHTMLOutput = '';
                myHTMLOutput += '<table class="persist-area">';
                     $(xml).find("group").each(function() {
                                                 
                                var groupDesc = $(this).find("desc").text();   
                                var groupSize = $(this).find("size").text();
                                   
                myHTMLOutput += '<tr><th>'+groupDesc+'</th><th>'+groupSize+'</th></tr>';
               
                // Run the function for each student tag in the XML file
                $(this).find("item").each(function() {
                        var groupName = $(this).find("name").text();
                        var groupPrice = $(this).find("price").text();
                                       
                        // Build row HTML data and store in string
                        myHTMLOutput += '<tr><td>'+groupName+'</td><td>'+groupPrice+'</td></tr>';
                }); /* End Item */
                               
               
        }); /* End Group */
                         myHTMLOutput += '</table>';
                         // Update the DIV called Content Area with the HTML string
              $("#mainContent").html(myHTMLOutput);
                         
  }); /* Function */   

});

reply

The Reddest
01/25/2012 - 09:50

I believe you're running into a security violation. The javascript is making a callback to a local resource (file://). Browsers don't typically like doing that because then any website can start reading files from a visitor's computer.

To test your application, you may have to run it in an actual web server. If you're on Windows, you can install and setup IIS fairly easily on your local machine.

reply

Anonymous
01/25/2012 - 13:01

1)Ok, I will upload the code to the server to check, but as far as the code is concerned, are you seeing anything that's out of the ordinary. Do you recomend the first version of javascript using .Ajax command or the second $.get('fullmenu2.xml'...2)Eventually I am planning on building a control panel for the client, where he would be able to edit/delete/add products in the xml file utilizing Ajax grid. Do you have a tutorial on that, or is there an existing uri component that could do the trick. Thank you for your prompt response.

reply

Anonymous
01/24/2012 - 21:37

can someone help?

reply

Anonymoussssssssssss
01/31/2012 - 17:58

How can I get for instance "Size 2" (namely the second group's size value) for the following xml?

I tried

$(this).find("group").each(function() {var size = $(this).find("size").text();}

but it did not get specifically the second group's size value. Should I use some other function instead of find or each?

<?xml version="1.0" encoding="utf-8"?>
<menu>
  <group>
    <desc>Full Breakfast (includes toast, home fries, coffee  or juice</desc>
    <size>Size 1</size>
    <item>
      <name>2 large eggs any style w/choice of bacon,  sausage or ham</name>
      <price>$ 5.75</price>
    </item>
  </group>
  <group>
    <desc>Omelets (All made with 3 large eggs includes toast,  home fries, coffee or juice)</desc>
    <size>Size 2</size>
    <item>
      <name>Cheese</name>
      <price>$ 5.60</price>
    </item>
    <item>
      <name>Smoked Virginia Baked ham and cheese</name>
      <price>$ 5.90</price>
    </item>
    <item>
      <name>Cured smoked bacon and cheese</name>
      <price>$ 5.90</price>
    </item>
    <item>
      <name>Sausage and Cheese</name>
      <price>$ 5.90</price>
    </item>
    <item>
      <name>Egg white w/5 vegetable fillings</name>
      <price>$ 6.70</price>
    </item>
    <item>
      <name>Western (ham, peppers and onions)</name>
      <price>$ 6.10</price>
    </item>
    <item>
      <name>Veggie with Cheese</name>
      <price>$ 6.40</price>
    </item>
    <item>
      <name>Spinach and Feta</name>
      <price>$ 5.95</price>
    </item>
  </group>
</menu>

reply

The Reddest
02/01/2012 - 09:58

You could try:

$(this).find('group')[1].find('size').text();

reply

Anonymous
02/13/2012 - 23:58

Somewhere there seems to be an error in what is in this page. As given, it does not work in Firefox or Safari.

reply

ben
04/13/2012 - 08:38

Love this. Thanks for sharing.

I've added a select options list. The value of the selected option is then used to define what it looks for in the xml file like this:

$(xml).find($("#DATE option:selected").val()).each(function () {
*....

It works great the first time the page loads, but I can't get it to fire again once a different option has been selected. I've tried adding a button that calls the parseXml function like this:

But it doesn't work. Feel like I'm close to getting it working but what am I missing??

Any help greatly appreciated!!

reply

Anonymous
05/02/2012 - 09:56

Hi,

code snippet given by you does not work in firefox, this question was already posted by some of the user in above conversation but no body has given the solution.Can you please tell me how to make it cross browser compatible.Thanks in advance

reply

seloh77
05/08/2012 - 05:56

Hi,

Thanks for this article, has great examples which I'm using.
I have one problem though, I have a path set in my XML and when parsing I get an error.
<option id="f783d1cb-60d8-82d3-9162-4heb96bf870d" name="path" value="E:\Users\admin\tmp\file_server" isPersistent="1" controlType="CheckBox" />
I don't have direct access to the XML, I know I have to replace the backslashes with double backslashes but when I try it with javascript it doesn't work.
If I manually replace the backslashes with double backslashes the script runs without errors and gives results.
I've tried the following techniques which make the script run without errors but without results:
xml = xml.replace('\\', '\\\\');
xml = xml.replace(new RegExp(/\\/g), '/');
xml = xml.replace(/\//g, '\\');

I'd think this wouldn't be this hard, is there something I'm missing?

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.