How To Read an XML file With Javascript Using JQuery

Even though JQuery does not provide a native function to read XML like it does for JSON it is still pretty easy to make your own, and that’s what we are going to do in this post.

Before we make this function though, you are going to have to learn how JQuery’s AJAX method works. In a previous post I showed you how to make AJAX applications using $.get, $.post and $().load, but to parse XML with javascript we need a function that does much more than what these do, we need $.ajax()

jQuery.ajax( options ) explained

This function has around 20 options and it would require a post all for itself so am just going to talk about the options we need, which are four, and move on.

To read an XML file we need to tell the function the location of the file, this is called the "url" in the function. We also need to specify the data type (dataType), in our case the data type is "xml". The last two options we need are "success" and "error", and these two options identify the functions we want to call upon success or error of reading the file respectively.

The XML file I will be using will be called "books.xml", the function we will use to parse the response will be called "parse" and our error function will be nothing more than an annoying alert function. So our $.ajax function set up will be the following.

$.ajax({
    url: 'books.xml', // name of file you want to parse
    dataType: "xml", // type of file you are trying to read
    success: parse, // name of the function to call upon success
	error: function(){alert("Error: Something went wrong");}
  });

The XML File We Want To Read

The JQuery function we’ll be making is specific to the XML file you want to read so we have to see the XML file first. Am going to use the XML file I made up and used in the post How to parse XML with PHP

Contents of the XML file:

<?xml version="1.0" encoding="UTF-8"?>
<library>
	<book isbn10="1234567890" isbn13="1234567890123">
		<title>PHP and MySQL</title>
		<author fname="miguel" lname="alvarez">Miguel Alvarez</author>
		<publisher>WebHole</publisher>
		<price>1.99</price>
	</book>
	<book isbn10="8957468873" isbn13="0984837828189">
		<title>JAVA 123</title>
		<author fname="william" lname="vega">WIlliam Vega</author>
		<publisher>WebHole</publisher>
		<price>2.99</price>
	</book>
</library>

Take a good look at the file before you move on, notice the attributes specially. What am going to do with javascript is display the ISBN10, Title and Author of each book. Now that you’ve identified these tags let’s go back to our JQuery script.

The XML-reading Javascript Function

It’s time to make our success function (parse). Our $.ajax set up returns the whole xml file as a document object, this means we can make use of a neat function called "find" that can be used to search documents and we will use this function to find the "books" tag. Once we have identified the tag we can use JQuery’s $.each function to loop through all the books in our file.

This is how the parse function looks so far.

function parse(document){
  $(document).find("book").each(function(){
     // this is where all the reading and writing will happen
  });
}

In your web page make sure you have a division (div) with an id "content" , this is where we will write our results to.

<div id="content"></div>

Inside the $.each loop every time we say $(this) we will be referring to the current book tag, it’s important that you keep this in mind. So in short, $(this) will represent <book>

To get the isbn10 attribute, which is an attribute for every book tag we would use the following line.

$(this).attr('isbn10');

To get the text inside another tag, in our book tag hierarchy , we have to use find first to find the tag. Let’s say you want to get the book’s title, this is what you would use.

$(this).find('title').text();
// which represents book->title

And this is what you would use to get the author.

$(this).find('author').text();

Now that you get the concepts let’s see how our whole scripts looks like, remember that the xml file is in the same folder. We will be making use of the function "append" to append the next to previous book.

<div id="content"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){


function parse(document){
  $(document).find("book").each(function(){
    $("#content").append(
	'<p>ISBN10: '+$(this).attr('isbn10')+
	'<br /> Title: '+$(this).find('title').text()+
	'<br /> Author: '+$(this).find('author').text()+
	'</p>'
	);
  });
}



  $.ajax({
    url: 'books.xml', // name of file you want to parse
    dataType: "xml",
    success: parse,
	error: function(){alert("Error: Something went wrong");}
  });
});
</script>

It’s important to note that $.ajax performs an HTTP GET request, if you want to make a POST request you can use the option "type" , in any case I would recommend reading the full documentation for this great function which can be found here.