HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

AJAX - Working with XML Files

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.


The responseXML Property

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();

Traversing the XML DOM

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;
}
Note: Browsers are very strict about XML formatting. If your XML file contains even a single syntax error (like an unclosed tag), responseXML will return `null`.

Extracting Child Nodes

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;
Pro Tip: When working with XML, ensure your server sends the correct Content-Type header: Content-Type: text/xml. If this is missing, some browsers might not populate the responseXML property.

Key Points to Remember

  • responseXML parses the server response into an XML DOM object.
  • Use getElementsByTagName() to locate specific data pieces.
  • XML files must be well-formed to be parsed correctly.
  • You can use standard DOM traversal techniques (parentNode, childNodes) on the XML result.
  • Always check if this.responseXML is not null before attempting to parse it.