Parsing XML using jQuery
Mon Nov 30 01:56:20 2009
I have found that being able to parse XML is one of the most useful things a programmer can learn. It allows you to store a lot of information in one place and easily edit it without the need to update your program or website itself. The effects on a website can be astounding.
Today, for those who don't know, I would like to show you how to parse XML files using jQuery. First, you will need an XML file. XML is a markup language and uses tags very similar to HTML tags. The major difference with XML tags is the fact that you get to choose the names of your tags.
I have created an xml file which will be a list of the websites I have recently created. The code is as follows:
<list> <item id="1"> <title>CuluCulu Flash</title> <url>http://www.culu-culu.com/culuculu/flash</url> </item> <item id="2"> <title>CuluCulu HTML</title> <url>http://www.culu-culu.com/culuculu/html</url> </item> <item id="3"> <title>Gakushu Support Juku</title> <url>http://www.supportjuku.com</url> </item> <item id="4"> <title>Yokkaichi College of Information & Languages</title> <url>http://www.ssc.ac.jp</url> </item> <item id="5"> <title>Tomojiro's Music Studio (v.2)</title> <url>http://www.musictomo.com</url> </item> </list>
As you can see, inside the
<list> tags there are five sets of
<item> tags, each containing a
<title> and a
<url>. What we want to do is parse the information in
<url> tags, which will allow us to create links. This is usefull to use for example in creating a sitemap for a list of urls to display on our website. Imagine you have 50 links you would like to display. Writing them out is quite a feet, let alone updating them. With a little jQuery, all of this becomes very simple.
Ok, so here's what's happening. We start off with the jQuery ready function (line 3) which initiates everything. Then, using the
$.ajax() method we tell jQuery to look for the sites.xml file (line 5) and give it the
dataType: "xml" so that it knows what kind of file we are dealing with (line 6). When jQuery has succeeded in finding and loading the file, it will call the anonymous inline function on line 7 and this is where we get to write what is going to happen with the information we have parsed.
On line 9 we loop through each of the
<item> tags and store the information inside the
<url> tags inside variables (lines 10 ~ 12).
To find attributes we use
('xx') is the name of the attribute we are looking for, which in this case is
'id' on line 10.
Finally, we use the info stored in each variable to output a little html inside the <div> tag with an id of 'content' using
HTML() on line 13, which in this case places the information inside a
href to create links. The output is as follows:
So there you go. Try it out and let me know how you get on. I also intend to write a post on AS3 xml parsing using the infamous E4X syntax, which is a delight to use. Until then, happy jQuery parsing!Tweet