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.
Source Files:
Very nice post
Be wary of namespaces!
http://www.zachleat.com/web/2008/05/10/selecting-xml-with-javascript/
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.
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!
should be
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.
can anyone help me to read this xml file please? I just took over from the previous developer.
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
Try posting the comment again. use the
language tag.
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.
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
Restructure your Xml-File like this:
You can access the xml tags with the following jQuery code:
Don't work with IE :(
i am making a video gallery. i found a flash template that creates xml file.
XML data looks this:
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...
I get confused at:
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?
the xml variable is passed into the function automatically by jQuery. parseXml is supplied to jQuery as part of the ajax request.
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)
(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?)
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...
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?
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:
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.
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"?
Thanks! David
GREAT, Could solve my problem with this great tutorial.
im having a problem with the find() function. For me it works in firefox and chrome perfectly, but any version of explorer returns 'undefinded'
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:
And then in my "success" function, I had to add this:
Thank you Timothy, it worked for me. Thanks a lot.... Happy Coding...
SoftXpath - Lightweight cross browser JavaScript library for querying complex XML documents using powerful Xpath expressions.
Demo
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: 1 1 John Doe 11111 Where Ever Yep MD 111111 111-111-1111 0
xml file 2:
1 testRZ
I would like to be able the grab all the order details and attach it to the orders.
I would create two objects to hold the information contained in the two XML files.
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.
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
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 [
] or the inner text of the element [
] to produces results.
I hope that somebody else can profit from that mistake ... alex
very nice post. thank you. bye.
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.
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
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).
Hi, I was wondering if anybody knows how to get a JSON response from an xml file using ajax.
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.
I tried...
(I also tried that with a success function that just said return xml; and got the same result)
I then call it like so...
The alert says "undefined"
What am I not getting?
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() :
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).
one two three
can anybody plese tell how to retrieve this xml.. i am using IE8 browser. I tried
but its not working.
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
Thank you so much =]
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 :
any kinda help is needed :)
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
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
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
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.
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.
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
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
Hello, I am trying to parse the XML given below.
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 ??
How does #output work?
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".
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.
I'm trying to read and parse a XML file from Google Finance API:
I have this Javascript:
However, I get an error:
Can anybody help solve the problem?
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.
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?
I have the Javascript file (jquery.js) residing on the same webserver as the index.html file.
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.
Hi, I am reading your tutorial but I cannot get my code to work is there something wrong you can spot? Please help me:
I feel so stupid, the code is good. I parse the wrong xml file. Please ignore my post above :(
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:
This is my Javascrip: [javascrip]
[/javascript]
what am i doing wrong?
Sorry the javascript file didnt come out right. Let me try again>
Does the Javascript error console say anything?
Yes it says: 'Uncaught SyntaxError: Unexpected token )' Is there some kind of a syntax error in the HTML code?
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.
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.
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:
can someone help?
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?
You could try:
Somewhere there seems to be an error in what is in this page. As given, it does not work in Firefox or Safari.
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!!
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
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.
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:
I'd think this wouldn't be this hard, is there something I'm missing?
Sorry if my question sounds like opening a Pandora's box but... I would like to simply be able to populate a description text in HTML from the same XML file loaded in Flash without the need to touch the HTML file itself, so that I can simply modify the XML to update the content in both versions of my website. I'm totally new to this and never found anything truly explaining how to do it. Does anybody know any source from where I can learn how to do what I need? Thanks in advance, I hope my question can help other people in my same situation... I'm sure are many!
hi, iam trying to populate states according to the countries.i.e if you select country.states should be populated in another dropdown according to the cound.but my code is displaying all the states irrespective of the countries.iam trying it in jquery. my xml file is
the above code is working if it is i used in server but not working locally
I am populating a Listview in jquery mobile from an xml file, but it is outputting all the xml fields into one li, instead of each xml record appearing in it's own li.
js snippet below
and the html listview code....
The listview list displays both the HEADING and BODY which is great, but it displays all three HEADINGS and BODY'S from the xml in the one list.
BTW: when i add
to the end of the append statement, it only shows one record from the xml file. aargh.
Can anyone help with the syntax?
Try this:
Hi Reddest,
Just browsing for xml jquery samples and reached on this page. Nice one and was pretty explaining...
I have a doubt on this. I just need to get the XML refreshed at even intervals for loading new values. Is this possible in JQuery.
Also updating the values in the the placeholder. Can you let me know any example on this.
Thanks in Advance...
I'm working a project that uses this method nicely. My question: the output is pulling a single portion of the XML file based on the date. For example, there's data for today and it's putting that data only. However, I'd like to see the previous dates data and the data for the tomorrow or two days from now (all predefined in the XML).
How would I go about making a "Previous/Next" rotating script
Impressed!.. Thanks for sharing this one..
is this code is compatible with IE browsers????
Šime on twitter answered it for you: "Cache the "#output" query". @simevidas is his twitter handle, if you would like thank him.