AJAX with XML File – Explained with Example
15 April 2025 | Category: JavaScript
What is XML?
XML (eXtensible Markup Language) is a structured format used to store and transport data. It’s similar to HTML, but it’s used more for data exchange between systems.
In modern development, JSON is more common, but XML is still used in many legacy systems and APIs.
🔄 How Does AJAX Work with XML?
You can use AJAX (via XMLHttpRequest
) to request an .xml
file and then read and display its content using JavaScript.
đź§Ş Sample XML File (data.xml
)
<books>
<book>
<title>JavaScript Essentials</title>
<author>John Doe</author>
</book>
<book>
<title>Learn AJAX</title>
<author>Jane Smith</author>
</book>
</books>
🚀 AJAX XML Example (Load and Display Data)
<!DOCTYPE html>
<html>
<head>
<title>AJAX XML Example</title>
</head>
<body>
<h2>Book List (Loaded from XML)</h2>
<button onclick="loadXML()">Load Books</button>
<div id="output"></div>
<script>
function loadXML() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onload = function () {
if (xhr.status === 200) {
const xmlDoc = xhr.responseXML;
const books = xmlDoc.getElementsByTagName("book");
let output = "<ul>";
for (let i = 0; i < books.length; i++) {
const title = books[i].getElementsByTagName("title")[0].textContent;
const author = books[i].getElementsByTagName("author")[0].textContent;
output += `<li><strong>${title}</strong> by ${author}</li>`;
}
output += "</ul>";
document.getElementById("output").innerHTML = output;
}
};
xhr.send();
}
</script>
</body>
</html>
đź“‘ Key Methods for Parsing XML
Method/Property | Description |
---|---|
xhr.responseXML | Returns the response as an XML Document |
getElementsByTagName("tag") | Returns a list of elements with that tag |
.textContent | Gets the text inside an element |
⚠️ Notes
- This example needs to be run on a local or live server, not directly from your file system (
file://
) due to browser security. - You can use Live Server in VS Code to test it easily.
đź§ Why Learn This?
Even though JSON is more popular now, knowing how to handle XML is useful when:
- Working with old APIs or government systems
- Integrating with enterprise tools
- Parsing large hierarchical data sets