Fetching XML Data from an External Source

In this approach, XML data is fetched from an external source, typically a server, using the fetch API.

  • Suitable for scenarios where XML data needs to be dynamically retrieved from a server.
  • Handles the response from the server using promises and interprets the response as text.
  • Proceeds with parsing the XML string similar to the direct parsing method after receiving the data from the server.

Example: The below code fetches XML data from external resource and parses it using JavaScript.

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <h1>
        How to Load XML from JavaScript?
    </h1>
    <script>
        fetch("tutorials.xml")
            .then((response) => response.text())
            .then((xmlString) => {
                const parser = new DOMParser();
                const xmlDoc = parser.
                    parseFromString(xmlString, "text/xml");

                const tutorials = xmlDoc.
                    querySelectorAll("tutorial");
                tutorials.forEach((tutorial) => {
                    const id = tutorial.
                        querySelector("id").textContent;
                    const title = tutorial.
                        querySelector("title").textContent;
                    console.log(
                        `Tutorial ID: ${id}, Title: ${title}`);
                });
            });
    </script>
</body>

</html>
XML
<!-- tutorials.xml  -->
<tutorials>
    <tutorial>
        <id>1</id>
        <title>Introduction to JavaScript</title>
    </tutorial>
    <tutorial>
        <id>2</id>
        <title>Advanced CSS Techniques</title>
    </tutorial>
</tutorials>

Output:

How to Load XML from JavaScript ?

Loading XML data into JavaScript is a common task, whether it’s for parsing user input or fetching data from a server.

The below-listed approaches can be used to load XML from JavaScript.

Table of Content

  • Parsing XML String Directly
  • Fetching XML Data from an External Source
  • Parsing XML in Node.js using xml2js

Similar Reads

Parsing XML String Directly

This approach involves directly parsing an XML string within the JavaScript code....

Fetching XML Data from an External Source

In this approach, XML data is fetched from an external source, typically a server, using the fetch API....

Parsing XML in Node.js using xml2js

In this approach, we utilize the xml2js module, which is specifically designed for parsing XML in a Node.js environment....