Last updated: 9th May 2024
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 can easily be distributed across the web. Here in this post, I'll show you how to extract or get data from an XML file using plain JavaScript.Data, in an XML file is a markup language and just by viewing it you know the type of data it stores. However, to read and extract XML from a file, you'll need a programming language like JavaScript (or a library like jQuery).
While talking about 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.
The XML File
Here's the file ... library.xml. I am going to use the data in the file in my example here.
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.
You can open file to view it. Copy the contents of the file and save it in your computer and name it as library.xml, because I am using the same file name in my example here. 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 a script to read and extract data from the file. The HTML DIV element is a lightweight container, so I decided to use a DIV element to display the XML data on my web page.
Tabular format
I want to display data in tabular format with couple of columns. The columns will show the Bookname and Category respectively.
<head> <style> #books { overflow: hidden; } #books div { width: 50%; } .col1 { float: left; clear: both; } .col2 { float:right; } </style> </head> <body> <div id="books"></div> </body> <script> let fetchLibrary = () => { const oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); function reportStatus() { if (oXHR.readyState == 4) { // request completed showTheList(this.responseXML); // Now show the data } } oXHR.onreadystatechange = reportStatus; oXHR.open("GET", "../../library/library.xml", true); // true = asynchronous request (desirable), false = synchronous request. oXHR.send(); } let showTheList = (xml) => { const divBooks = document.getElementById('books'); // parent element. const book_List = xml.getElementsByTagName('List'); // the xml tag name for (let i = 0; i < book_List.length; i++) { // Create child DIVs inside parent DIV. let divLeft = document.createElement('div'); divLeft.className = 'col1'; divLeft.textContent = book_List[i].getElementsByTagName("BookName")[0].childNodes[0].nodeValue; let divRight = document.createElement('div'); divRight.className = 'col2'; divRight.textContent = book_List[i].getElementsByTagName("Category")[0].childNodes[0].nodeValue; // add child to parent. divBooks.appendChild(divLeft); divBooks.appendChild(divRight); } }; fetchLibrary(); </script>
Here's the output.
In-addition, you can read and write XML data using C# and Vb.Net in Asp.Net
Once the web page has loaded, it will make an XML request using http, 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 side languages like JavaScript, JScript and even 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 http.
onreadystatechange Property
Sets or retrieves the event handler for asynchronous requests. onreadystatechange property was first introduced in IE 7.
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 )
You can read more about the open() method here.
The send() Method
Call this method to send an http request. The "send" method accepts only one parameter called the data, and we are not using it.
Syntax
send ( data )
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, quickly. Though the name suggests XML, we can use this object and its properties to extract data from other sources like HTML or plain text.