Parse XML using JavaScript

Understanding how to parse XML data using JavaScript can significantly improve your capability to handle and display structured data on web pages. XML, or Extensible Markup Language, is widely used for data interchange and configuration files. By learning how to convert XML strings into JavaScript objects, you can efficiently access and manipulate data, allowing for more dynamic and data-driven web applications. In this tutorial, you’ll learn how to effectively parse XML and present the extracted information, enhancing your web projects’ functionality and user experience.

Guide on how to parse XML

Create an XML file containing data as follows

<data>
  <item>
    <name>Bowl</name>
    <description>Used to transfer food or ingredients to. </description>
    <price>10.00</price>
  </item>
  <item>
    <name>Frying Pan</name>
    <description>Used for cooking food.</description>
    <price>25.50</price>
  </item>
</data>

Save the XML  file and create a HTML  file with needed CSS selectors and attributes for styling.

Lets create a button so that when it is clicked it displays the data from XML file on the webpage.

<button onclick="parseXML()">Parse XML</button>

The onclick attribute specifies that when the button is clicked, the parseXML() function should be executed.

Then we create a div element with the id output. This div will be used to display the parsed XML content.

<div id="output"></div>

Then we write the JavaScript code which will actually parse the XML content.

function parseXML() {
  var xmlhttp = new XMLHttpRequest();

These lines defines the parseXML function and create a new instance of XMLHttpRequest to handle the HTTP request.

xmlhttp.onreadystatechange = function() {

Assigns an anonymous function to handle changes in the readyState of the xmlhttp object.

if (this.readyState == 4 && this.status == 200) {
      var xmlString = this.responseText;

Checks if the request is complete (readyState == 4) and successful (status == 200) and also stores the response text (the XML file content) in the xmlString variable.

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");

Creates a new DOMParser object. Parses the XML string into an XML document object (xmlDoc).

var items = xmlDoc.getElementsByTagName("item");
var output = "";

Retrieves all <item> elements from the XML document. Initializes an empty string output to accumulate the HTML content.

for (var i = 0; i < items.length; i++) {
        var name = items[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
        var description = items[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
        var price = items[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;

Loops through each <item> element. Retrieves the text content of the <name>, <description>, and <price> elements within each <item>.

output += `
          <div class="item">
            <b>Item ${i + 1}:</b>
            <div>Name: ${name}</div>
            <div>Description: ${description}</div>
            <div>Price: Rs. ${price}</div>
          </div>
        `;
      }

Appends a new block of HTML to the output string for each item. Each block includes the item number, name, description, and price.

ocument.getElementById("output").innerHTML = output;
    }
  };
  xmlhttp.open("GET", "note.xml", true);
  xmlhttp.send();
}

Closes the loop. Sets the inner HTML of the output div to the accumulated output string. Opens an asynchronous GET request to fetch note.xml. Sends the request.

Then we finally close the <script> tag and close the <body> and <html> tags and save the file.

Results

When we run the program we get the folllowing webpage.

When we click on the Parse XML button, the parseXML function fetches the webpage data and parses the XML file it directs to and then displays the parsed XML file as follows.

 

This way we are able to parse a XML file using JavaScript.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top