Last update: 12th March 2023
In my previous article I have shared an example on how to extract data from an XML file using JavaScript and XMLHttpRequest object. Now, here in this article I'll show you how to extract and read XML data from a file using jQuery Ajax.The XML Data
First create an XML file (with .xml extension). You can copy data from this file. No problem if you have a different list or format, however, just be careful while defining the nodes in your script.
🚀 Do you know...
You can do this using Plain old JavaScript. Or, you can use modern (and more efficient) JavaScript methods like async and await to read XML data from a file.
The Markup and the Script
Add a <div> element inside the <body> tag of the page. Since, we'll be showing the extracted XML data inside the <div> element.
<body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script> <input type="button" value="Click to show XML data!" id="bt" /> <!--data will be displayed here...--> <div id="books"></div> </body> <script> $(document).ready(function() { $('#bt').click(function () { $('#books').empty(); // Clear the DIV. $.ajax({ type: 'GET', url: '../../library/library.xml', // The file path. dataType: 'xml', success: function(xml) { $(xml).find('List').each(function() { const bookName = $(this).find('BookName').text(); const category = $(this).find('Category').text(); const price = $(this).find('Price').text(); // Append new data to the DIV element. $('#books').append(` <div> <div><b>Name of Book: </b>${bookName}</div> <div><b>Category: </b>${category}</div> <div><b>Price: </b>${price}</div> </div> `); }); } }); }); }); </script> </html>
In the above script, I am making a simple GET request (for data) using jQuery Ajax. I have also assigned the "URL" of the XML file along with the dataType.
If request is successfull, it will recieve an XML document. jQuery will traverse through each "List tag" in the DOM tree and append the values of each attribute inside the tag (XML tag) to the DIV element.
Populate XML Data in an Asp.Net ListBox
Using similar method (see above example) we can populate data extracted for an XML file to a Asp.Net listbox control or a dropdownlist control.
Drag and drop a ListBox control (from the Asp.Net toolbox) in your web page and write the below code to extract and populate data to the ListBox.
<!DOCTYPE html> <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div> <asp:ListBox ID="lstBooks" Width="300px" runat="server"></asp:ListBox> </div> </body> <script> $(document).ready(function() { $.ajax({ type: 'GET', url: 'library.xml', dataType: 'xml', success: function(xml) { $(xml).find('List').each(function() { $('#lstBooks') .append($('<option />') .text($(this) .find('BookName').text())); }); } }); }); </script> </html>