Although JSON has become more popular, XML (eXtensible Markup Language) is still widely used for data interchange. AJAX allows you to request an XML file, parse its contents using standard DOM methods, and display it inside your web page.
When the server responds with XML, the XMLHttpRequest object provides the
responseXML property. This property treats the incoming data as an XML DOM
object, which you can navigate just like an HTML document.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Access the XML DOM
var xmlDoc = this.responseXML;
parseXml(xmlDoc);
}
};
xhttp.open("GET", "catalog.xml", true);
xhttp.send();
Since the XML is treated as a DOM, you can use familiar methods like
getElementsByTagName() to extract data.
function parseXml(xml) {
var x = xml.getElementsByTagName("CD");
var table = "<tr><th>Artist</th><th>Title</th></tr>";
for (var i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
responseXML will return `null`.
To get the text content of an XML element, you specifically look for its
childNodes[0].nodeValue or use the more modern textContent
property.
// Old way (widely compatible)
var val = xml.getElementsByTagName("NAME")[0].childNodes[0].nodeValue;
// Modern way
var val = xml.getElementsByTagName("NAME")[0].textContent;
Content-Type: text/xml. If this is missing, some
browsers might not populate the responseXML property.