← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 15 of 26

JS AJAX XML

While modern AJAX overwhelmingly uses JSON, some servers and legacy APIs still return actual XML -- and browsers provide built-in tools (responseXML on XMLHttpRequest, or DOMParser for fetch-based requests) to parse that XML response into a navigable document, the same DOM structure an HTML page itself uses.

Reading responseXML from XMLHttpRequest

XMLHttpRequest automatically parses an XML response body into a Document object, available as xhr.responseXML, provided the server sent an XML-appropriate Content-Type header -- no manual parsing step required, unlike with fetch.

Note: Confirm the server is actually sending an XML content type if responseXML unexpectedly comes back null despite the body clearly being XML text.

Warning: responseXML remains null if the server's Content-Type header does not indicate XML, even if the raw response text is valid, well-formed XML.

Example: Reading responseXML from XMLHttpRequest

javascript
const xhr = new XMLHttpRequest();
xhr.onload = () => console.log(xhr.responseXML); // parsed automatically
xhr.open("GET", "data.xml");
xhr.send();

Parsing XML with fetch and DOMParser

fetch does not have an equivalent to responseXML -- an XML response must be read as plain text with response.text(), then parsed manually into a Document using new DOMParser().parseFromString(text, 'text/xml').

Note: Always specify 'text/xml' (or 'application/xml') as the MIME type argument to parseFromString, so DOMParser knows to parse it as XML rather than HTML.

Warning: DOMParser inserts a special <parsererror> element into the resulting document rather than throwing a catchable exception on malformed XML -- check for it explicitly.

Example: Parsing XML with fetch and DOMParser

javascript
fetch("data.xml")
  .then(response => response.text())
  .then(text => new DOMParser().parseFromString(text, "text/xml"))
  .then(doc => console.log(doc));

Navigating a Parsed XML Document

Once parsed (via either responseXML or DOMParser), an XML response behaves like any other DOM document -- querySelector(), querySelectorAll(), and getElementsByTagName() all work identically to how they work on an HTML page.

Note: Use the same DOM traversal methods you already know from HTML pages when working with a parsed XML document -- no separate XML-specific API to learn.

Warning: XML tag names are case-sensitive, unlike HTML, so querySelector("Title") and querySelector("title") can match entirely different elements in an XML document.

Example: Navigating a Parsed XML Document

javascript
const xmlText = "<root><item>Test</item></root>";
const doc = new DOMParser().parseFromString(xmlText, "text/xml");
console.log(doc.querySelector("item").textContent);

Comparing XML and JSON Responses

Converting an existing XML-based endpoint's response to JSON is often worth doing for new features, since JSON parses into plain JavaScript objects/arrays automatically, requiring none of the manual DOM-style navigation XML needs -- but reading existing XML endpoints remains a real, occasional necessity.

Note: For a brand-new endpoint you control, prefer JSON; reserve XML-handling code specifically for endpoints where XML is already the established format.

Warning: Converting an existing, working XML-based system to JSON is a larger undertaking than it might first appear, especially if other consumers of that XML endpoint cannot be changed at the same time.

Example: Comparing XML and JSON Responses

javascript
const doc = new DOMParser().parseFromString("<root><item>1</item></root>", "text/xml");
console.log(doc.getElementsByTagName("item")[0].textContent);
console.log(JSON.parse('{"item": 1}').item);

A Practical XML AJAX Example

Combining the pieces: fetching an RSS-style XML feed, parsing it with DOMParser, and looping over its repeated <item> elements to build a simple list of headlines -- a realistic, complete example of consuming an XML-based AJAX endpoint end to end.

Note: Build and test XML-parsing code incrementally: confirm the fetch and parse succeed first, then add the loop and rendering logic afterward.

Warning: An RSS or XML feed from an external source is outside your control and can occasionally change structure -- defensive checks (confirming an expected element exists before reading it) help avoid a broken page from an unexpected format change.

Example: A Practical XML AJAX Example

javascript
fetch("feed.xml")
  .then(r => r.text())
  .then(text => {
    const doc = new DOMParser().parseFromString(text, "text/xml");
    doc.querySelectorAll("item").forEach(item => console.log(item.textContent));
  });
Common Mistakes
  1. Trying to use response.json() on an XML response, which fails since the body is not valid JSON -- XML responses must be read as text and parsed separately.
  2. Forgetting that responseXML (on XMLHttpRequest) is only populated automatically if the server sends the correct Content-Type header for XML.
  3. Not checking for a parser error in the resulting document, which DOMParser inserts as a special element rather than throwing a catchable exception.
Chapter Summary
  • XMLHttpRequest automatically parses an XML response into responseXML if the server's Content-Type header indicates XML.
  • For fetch, an XML response must be read with response.text() and then parsed manually using the built-in DOMParser.
  • Once parsed, an XML response can be navigated with the same DOM methods (querySelector, getElementsByTagName) used on an HTML document.
Browser Support

XMLHttpRequest.responseXML and the DOMParser API are both supported in every modern browser.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.