jquery

http://www.compoc.com/tuts/

Easy XML Consumption using jQuery

With the popularity of AJAX Web 2.0 style applications and the increase in web services it has become increasingly important to be able to parse XML from the client browser. This is not the easiest thing to do in a cross browser manner without the aid of a JavaScript library that supports XML. Fortunately jQuery makes XML utilization (almost) effortless. If you possess a basic understanding of how to program JavaScript then this tutorial will have you working with XML in 20 minutes.

To get started you will want to make some basic preparations:

  1. Make sure you use Firefox to run these examples. While you can certainly use IE, Firefox is less restrictive when it comes to running JavaScript from your local machine.
  2. Create a new directory for the sample files on your machine.
  3. Download the latest version of jQuery. Make sure to rename the file to jquery.js so it will work with these examples (by default the name will include the version and look something like jquery-1.2.3.min.js) and place the file into the root of the project directory you created.
  4. Download the following sample files and place the contents into the root of your project directory.
  5. Grab your favorite text editor or IDE and open those three files up. I recommend Notepad++ or Aptana.

The XML Data File

Below is a stripped down example of the XML file included. I assume you already know the basics of what XML is and how it is formed so I will only provide a quick breakdown of the most complex tag for those that need a light refresher. If you know basic XML you can skip this. Those unfamiliar with XML should check out SitePoints article titled "A Really Really Really Good Introduction to XML"

A. An xml tag. In this case the tag's title is "name"
B. A tag attribute named "post" which is assigned a value of "Class President"
C. The text inside the "name" tag with the value of "Gina Smith"

The HTML File

There is not much that is special about our html file. I kept it as clean as possible so you could concentrate on the JavaScript file that contains the jQuery code. Below are the only two portions of the html file that warrant some explanation.

The two lines of code illustrated above loads the jQuery library and our readXML JavaScript example.

I created a simple DIV that I called "ContentArea". Right now the DIV is blank. That will change when we dynamically update this object inside of the readXML JavaScript once the page has loaded.

The JavaScript readXML file

This is the file where most of the action is taking place. The jQuery library may make it easy to parse XML among many other things (that are also made equally simple) but the language tends to encourage the creation of compound functions which can make it a bit difficult to decipher for a newcomer. Not to worry, I have taken a few steps to make the information easier to digest:

  1. Color coded the examples to make following along more straight forward.
  2. Created short mini examples where each jQuery element is dissected.

The commands presented are the same as what you see in the readXML file but I have done my best to isolate them from any other code that does not help illustrate the jQuery concepts. Go ahead and minimize the readXML file if you have it open right now and concentrate on the mini-example below. When you open it back up in a few minutes you should have a better understanding of what the jQuery functions are doing.

The very colorful example below will wait until the DOM has loaded, read the students.xml file, cycle through each student record and store the name tag text into a variable. What we are not doing (yet) is anything useful with that data such as dynamically populating it into that empty DIV in the HTML file or storing the values in an array. Each time you see a change in color you are looking at a function within a function (and sometimes even those are within other functions).

 Note: Whenever you see a $, that is a shortcut for the function jQuery(). So $(document)… is the same as jQuery(document). This is good to know if you plan to use jQuery in tandem with another library such as prototype that uses the $ symbol as a shortcut.

The code segment below acts in a capacity similar to JavaScript's windows.onload statement. In this example we want to run our function once the DOM has been loaded.

A. $(document) – The document element refers to the DOM for the HTML page. The period tells us that the statement following should be applied to the selected element.
B. .ready – The ready command tells us that once the selected element "document" is ready to perform the actions within the parenthesis.
C. function() – This command creates and runs an unnamed function which includes everything encapsulated inside the brackets.

Note: Having no name for the function is ok if you just need to run it and won't need to reference it by name. If we wanted we could have given the function a name rather than leaving it blank.

Next we want to read the student.xml file and run a function that will be called "xml".

A. $.get – Runs the jQuery get function based on the parameters inside the parenthesis.
B. "students.xml" – The name of the file we are grabbing.
C. {} – Optional parameters left blank which we will not be taking advantage of in this tutorial.
D. function(xml) – Create a function named "xml" which encapsulates everything within the brackets that follow.

Note: We could have named this anything, I chose "xml" to be descriptive but in reality I could just as easily named it something else such as "studentRecords". Note: I chose to use the high level Ajax $.get function in jQuery. I could have just as easily used the $.post command or the lower level and more powerful (but not quite as simple to use) $.ajax command. Please see the Ajax section of the jQuery documentation for more information.

Each time we encounter the tag "student" in the file we will create and run an instance of a function which will be named "i".

A. $('student',xml) – Grab all 'student' tags from the xml object.
B. .each – Do whatever is within the ()'s one time for each instance of the statement to the left.
C. function(i) – Create a function named i running everything within the brackets

Note: In this statement I chose to assign the function with a name of "i" even though it is never referenced by name. You could delete the "i" leaving the function name blank and the code will still work as the current unnamed function can still be referenced by the "this" keyword.

Last we assign the text inside the "name" tag to the variable called "studentName".

A. studentName – The name of the variable we are assigning the value to.
B. $(this) – This function. (We are referring to the function we just created named 'i')
C. .find("name") – Find all instances of the "name" tag within the "student" tag. (We are making the assumption there will only be a single "name" tag within this instance of the "student" tag.)
D. .text() – Convert the value to text.

Now that you understand the snippet above let me introduce you to a few more jQuery commands that you might find useful before you take another look at the readXML code.

Grabbing XML tag attributes with jQuery

Capturing an XML attribute with jQuery is almost as simple as grabbing the text in between the tag. The code below is similar to the last line of code displayed. I'm only going to dissect the portion of the command that is different from the previous example where we were grabbing the tag text. Below we capture an XML tag attribute value.

A. .attr("post") – This grabs the attribute value titled "post".

Updating the content of a DIV dynamically

Once we know how to grab the data, we need to be able to display it. The following command will update a DIV tag populating it with the information contained in a string.

A. $("#ContentArea") – Selects the HTML element with an ID of "#ContentArea" (The DIV tag we created in the HTML example).
B. .append(myHTMLOutput) – adds the string assigned to the variable myHTMLOutput to the selected tag.

Another look at the JavaScript readXML file

Run the index.html file if you have not done so already. You should see the xml data organized in a table.

Open up that readXML file and take a second look. The jQuery commands should look more familiar to you. The extra code not featured in the tutorial is either straight JavaScript or jQuery commands that are very similar to what you have already seen.

When looking at the code the important thing for you to make note of is where the extra JavaScript code has been placed. I chose to build my HTML (which I eventually populate into the empty DIV) in one string variable. It was important that I created the string variable and populated it with the beginning table code including the header row before the $('student,xml).each statement. This ensures that the information is updated only once before the reading of the XML record begins.

You will also notice that I have created a function to help build the HTML string variable that I named BuildStudentHTML. This is just regular run of the mill JavaScript code. The only code in that function you may want to take note of is the if statement. I evaluate the variable "studentPost". If the "name" tag does not have the "post" attribute then it will be undefined. This provides me a means of discriminating between instances of the "name" tags that do and do not possess this attribute when evaluated.

Another thing I do is place my HTML table closing tag into the string variable after the closing of the $('student,xml).each statement, since we only want to add the end table tag information to the string once. Last we update our DIV populating it with the HTML string we built in our jQuery code.

Summary

You should now be able to adapt what you have learned to parse XML files with ease utilizing jQuery. This tutorial only scratches the surface of what this dynamic JavaScript library is capable of. For more information check out the reference links provided below.

Reference

SitePoint Articles:

Other References:

--
Thanks
Suresh Devaraj