← 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.
Syntax
javascript
const xmlDoc = xhr.responseXML;
const nodes = xmlDoc.getElementsByTagName("tag");
nodes[0].childNodes[0].nodeValue;

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.

उदाहरण: 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.

उदाहरण: Parsing XML with fetch and DOMParser

javascript
// Define the method `fetch` taking `"data.xml"`
// Define the method `fetch` taking `"data.xml"`
fetch("data.xml")
  // On success, run this with the resolved value as `response`
  // On success, run this with the resolved value as `response`
  .then(response => response.text())
  // On success, run this with the resolved value as `text`
  // On success, run this with the resolved value as `text`
  .then(text => new DOMParser().parseFromString(text, "text/xml"))
  // On success, run this with the resolved value as `doc`
  // On success, run this with the resolved value as `doc`
  .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.

उदाहरण: Navigating a Parsed XML Document

javascript
// Declare the constant `xmlText`, set to "<root><item>Test</item></root>"
// Declare the constant `xmlText`, set to "<root><item>Test</item></root>"
const xmlText = "<root><item>Test</item></root>";
// Declare the constant `doc` as a new `DOMParser` instance
// Declare the constant `doc` as a new `DOMParser` instance
const doc = new DOMParser().parseFromString(xmlText, "text/xml");
// Print `doc.querySelector("item").textContent` to the console
// Print `doc.querySelector("item").textContent` to the console
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.

उदाहरण: Comparing XML and JSON Responses

javascript
// Declare the constant `doc` as a new `DOMParser` instance
// Declare the constant `doc` as a new `DOMParser` instance
const doc = new DOMParser().parseFromString("<root><item>1</item></root>", "text/xml");
// Print `doc.getElementsByTagName("item")[0].textContent` to the console
// Print `doc.getElementsByTagName("item")[0].textContent` to the console
console.log(doc.getElementsByTagName("item")[0].textContent);
// Print `JSON.parse('{"item": 1}').item` to the console
// Print `JSON.parse('{"item": 1}').item` to the console
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.

उदाहरण: A Practical XML AJAX Example

javascript
// Define the method `fetch` taking `"feed.xml"`
// Define the method `fetch` taking `"feed.xml"`
fetch("feed.xml")
  // On success, run this with the resolved value as `r`
  // On success, run this with the resolved value as `r`
  .then(r => r.text())
  // On success, run this with the resolved value as `text`
  // On success, run this with the resolved value as `text`
  .then(text => {
    // Declare the constant `doc` as a new `DOMParser` instance
    // Declare the constant `doc` as a new `DOMParser` instance
    const doc = new DOMParser().parseFromString(text, "text/xml");
    // Call `doc.querySelectorAll("item").forEach(item => console.log(item.textContent))`
    // Call `doc.querySelectorAll("item").forEach(item => console.log(item.textContent))`
    doc.querySelectorAll("item").forEach(item => console.log(item.textContent));
  });
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.