Open In App

How to Access XML Data via JavaScript ?

XML stands for Extensible Markup Language. It is a popular format for storing and exchanging data on the web. It provides a structured way to represent data that is both human-readable and machine-readable.

There are various approaches to accessing XML data using JavaScript which are as follows:

Using DOM Parser

Document Object Model (DOM) Parser in JavaScript provides a way to parse XML or HTML documents into a tree-like structure.

Example: To demonstrate accessing XML data via JavaScript DOM parser.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Using DOM Parser</title>
</head>
<body> 
    <script>
        // Sample XML data
        const xmlString = `
            <root>
                <person>
                    <name>John</name>
                    <age>30</age>
                </person>
                <person>
                    <name>Alice</name>
                    <age>25</age>
                </person>
            </root>`;

        // Create a new DOMParser
        const parser = new DOMParser();

        // Parse the XML string
        const xmlDoc = parser
        .parseFromString(xmlString, "text/xml");

        // Access elements using DOM methods
        const persons = xmlDoc
        .getElementsByTagName("person");

        // Loop through elements
        for (let i = 0; i < persons.length; i++) {
            let name = persons[i]
            .getElementsByTagName("name")[0]
            .childNodes[0]
            .nodeValue;
            let age = persons[i]
            .getElementsByTagName("age")[0]
            .childNodes[0]
            .nodeValue;
            console.log("Name:", name, "Age:", age);
        }
    </script>
</body>
</html>

Output:

Name: John Age: 30
Name: Alice Age: 25

Using XMLHttpRequest

XMLHttpRequest is a built-in JavaScript object used to make HTTP requests to server-side resources. It can be used to fetch XML data from a server asynchronously.

Example: To demonstrate accessing XML data using XMLHttp request.

//data.xml
<bookstore>
<book>
<title>Database</title>
<author>abc</author>
</book>
<book>
<title>Data Structure</title>
<author>xyz</author>
</book>
</bookstore>

Example: To demonstrate fetching XML data from the server using the XMLhttps request.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Using XMLHttpRequest</title>
</head>
<body> 
   <script>
    const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function ()
         {
            if (this
            .readyState == 4 
            && 
            this.status == 200) {
                let xmlDoc = this.responseXML;
                let titles = xmlDoc
                .getElementsByTagName("title");
                let author = xmlDoc
                .getElementsByTagName("author");
                for (var i = 0; i < titles.length; i++) {
                    console.log(`${titles[i]
                        .childNodes[0]
                        .nodeValue} Book is written by ${author[i]
                            .childNodes[0]
                            .nodeValue} `);
                }
            }
        };
        xhttp.open("GET", "data.xml", true);
        xhttp.send();
   </script>
</body>
</html>
<!--  Save this file in same 
root folder as data.xml file  -->
<bookstore>
  <book>
    <title>Database</title>
    <author>abc</author>
  </book>
  <book>
    <title>Data Structure</title>
    <author>xyz</author>
  </book>
</bookstore>

Output:

Database Book is written by abc 
Data Structure Book is written by xyz
Article Tags :