Ajax Xml File in JavaScript
? Using AJAX to Read an XML File in JavaScript
AJAX can load and parse an .xml file from the server and extract data from it using JavaScript.
? Example Overview
You will:
Create an XML file (
data.xml)Use JavaScript to load and parse it via AJAX
Display the XML data in the browser
? 1. XML File (data.xml)
<users> <user> <name>Alice</name> <email>alice@example.com</email> </user> <user> <name>Bob</name> <email>bob@example.com</email> </user></users>? 2. HTML + JavaScript (index.html)
<button onclick="loadXML()">Load XML</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 users = xmlDoc.getElementsByTagName("user"); let output = ""; for (let i = 0; i < users.length; i++) { const name = users[i].getElementsByTagName("name")[0].textContent; const email = users[i].getElementsByTagName("email")[0].textContent; output += `<p><strong>${name}</strong>: ${email}</p>`; } document.getElementById("output").innerHTML = output; } }; xhr.send();}</script>? Output Example
Alice: alice@example.com Bob: bob@example.com? Notes
xhr.responseXMLautomatically parses XML into a DOM document.You can navigate it like HTML DOM using
getElementsByTagName().Works best when the XML file is on the same domain/server.
?? Common Use Cases for XML AJAX
| Use Case | Why XML? |
|---|---|
| Legacy APIs | Some APIs still return XML |
| Configuration files | Older apps use .xml for setup |
| Data interchange | Sometimes used in enterprise apps |
Would you like to see this done using fetch() instead of XMLHttpRequest, or a version that parses RSS feeds using AJAX?