Tags:
create new tag
view all tags

How To Read an XML file With Javascript Using JQuery

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

Before we make this function though, you are going to review how JQuery’s AJAX method works. To parse XML with javascript we need to use $.ajax()

jQuery.ajax( options ) explained

This function has around 20 options and it would require a post all for itself so we will just review 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 we 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. Below is a simple XML file of books.

Contents of the XML file:

<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book isbn10="1234567890" isbn13="1234567890123">
    <title>XML for Kenyon</title>
    <author fname="james" lname="skon">James Skon</author>
    <publisher>Kenyon Review</publisher>
    <price>1.99</price>
  </book>
  <book isbn10="8957468873" isbn13="0984837828189">
    <title>C++ on the hill</title>
    <author fname="Noah" lname="Aydin">Noah Aydin</author>
    <publisher>Kenyon Review</publisher>
    <price>2.99</price>
  </book>
</library>

Look at the file before you move on, notice the attributes specially. What we will do with javascript is to 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

First we make an $.ajax 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="https://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>

You can read more about the $ajax function here.

Things to try:

  1. Make a file books.xml and copy in the content fom above
  2. Make a file book.html and copy in the code from above.
  3. Copy the files to /var/www/html/class/softdev/your-username/
  4. Try it out
  5. Add 2-3 more books to the xml file with YOU as the author
  6. Modify the program to only print out books by you
  7. Modify the program to have a input field, and to find the books by the author typed in.
  8. Modify the program to find and display information on a book with a given isbn10 number.
Topic revision: r1 - 2017-04-12 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback