Extract Data from an XML File Using JavaScript

XML is in use for a very long time and used worldwide for its simplicity and the friendliness it provides to developers. The core purpose of designing XML was to create web pages. It also serves as a lightweight data source, and easily distributed across the web.

xmlhttprequest

Also Read: You can also extract or read data from an XML file using jQuery and Ajax

Data written in an XML file is a markup language and even by viewing it, we can figure out the type of data it has stored. However, we need to extract the data programmatically using JavaScript (and jQuery), which can later be display on a web page.

While taking a dig on XML, the very first thing comes into our minds in AJAX (Asynchronous JavaScript and XML) and this is what we will discuss in this article.

Let us first look at a typical XML file filled with data. The file has a list of Books, put together using XML attributes, tags and nested tags.

Note: The tags are case sensitive and you should use it carefully in your program.

The XML File

You can open library.xml file to view it. Copy the contents of the file and save it in your computer and name it as library.xml, because we are using the same file name in our example. You can change the name of the file according to your choice later.

Extract Data from XML

After creating the XML file (also called XML document), we will write JavaScript to read and extract data from the file. The HTML DIV element is a lightweight container, so we decided to use a DIV element to display the XML data on our web page.

Tabular format

We want to display data in a tabular format with couple of columns. The columns will show the Bookname and Category respectively.

To show data in tabular formats (i.e. in two columns), we need to use two more DIV elements inside the main DIV, which serves as a container. We will use CSS to place both the DIV elements side-by-side.

The Markup with the Script
<html>
<head>
    <title>Extract XML Data using JavaScript</title>
    <style>
        body {font:14px Calibri;}
        #books {
            width:390px;
            text-align:center;
            border:solid 1px #000;
            overflow:hidden;
        }
        #books div {
            width:180px;
            text-align:left;
            border:solid 1px #000;
            margin:1px;
            padding:2px 5px;
        }
        .col1 {
            float:left;
            clear:both;
        }
        .col2 {
            float:right;
        }
    </style>
</head>
<body>
    <p>Data extracted from an <b>XML</b> file</p>
    <div id="books"></div>
</body>

<script>
    var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

    function reportStatus() {
        if (oXHR.readyState == 4)               // REQUEST COMPLETED.
            showTheList(this.responseXML);      // ALL SET. NOW SHOW XML DATA.
    }

    oXHR.onreadystatechange = reportStatus;
    oXHR.open("GET", "../../library/library.xml", true);      // true = ASYNCHRONOUS REQUEST (DESIRABLE), false = SYNCHRONOUS REQUEST.
    oXHR.send();

    function showTheList(xml) {

        var divBooks = document.getElementById('books');        // THE PARENT DIV.
        var Book_List = xml.getElementsByTagName('List');       // THE XML TAG NAME.

        for (var i = 0; i < Book_List.length; i++) {

            // CREATE CHILD DIVS INSIDE THE PARENT DIV.
            var divLeft = document.createElement('div');
            divLeft.className = 'col1';
            divLeft.innerHTML = Book_List[i].getElementsByTagName("BookName")[0].childNodes[0].nodeValue;

            var divRight = document.createElement('div');
            divRight.className = 'col2';
            divRight.innerHTML = Book_List[i].getElementsByTagName("Category")[0].childNodes[0].nodeValue;

            // ADD THE CHILD TO THE PARENT DIV.
            divBooks.appendChild(divLeft);
            divBooks.appendChild(divRight);
        }
    };
</script>
</html>
Try it

Also Read: How to read and write XML Data using Asp.Net C# and Vb.Net

Output

Extract Data from XML using JavaScript

What's inside the Code?

Once the web page has loaded, it will make an XML request using https, which means it is asking for an XML file. We are using the XMLHttpRequest object and other members to make this request.

XMLHttpRequest Object

This object is one of the key features of AJAX. We can use XMLHttpRequest and its properties with many client languages like JavaScript, JScript and other server side languages, to communicate with XML files and its data. We can transfer and manipulate data from various sources in the web server using https.

onreadystatechange Property

Sets or retrieves the event handler for asynchronous requests. onreadystatechange property was first introduced in IE 7.

readyState Property

This readyState property will define the current state of request operation or the request made by XMLHttpRequest object.

Values of readyState Property

State

0
1
2
3
4

Description

Uninitialized. Not yet initialized, but an object is created.
The request has been setup. The object is created, send method not yet called.
We have sent a request.
The sent request is still in process.
The request is complete and ready to process further.



The open() Method

We must initialize the XMLHttpRequest object through the “open” method. This method takes five parameters. However, we have used three parameters in our example.

Syntax

open ( Method, URL, Asynchronous, UserName, Password )

We suggest you read more about the open() method here.

The send() Method

Call this method to send an https request. The “send” method accepts only one parameter called the data, and we are not using it.

Syntax

send ( data )

Conclusion

XMLHttpRequest object with AJAX has made web developing a boon for developers and at the same time benefited the users due to the Asynchronous processing capabilities of data, which is quick. Though the name suggests XML, we can use this object and its properties to extract data from other sources like HTML or plain text.

Previous - How to Restrict or Disable Browser Back Button Using JavaScriptNext - Greet your Visitors with Good Morning, Good Afternoon or Good Evening Message using JavaScript



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts: