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.
Example: The below code fetches XML data from external resource and parses it using JavaScript.
<!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>
<!-- 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