TExcelTAD
Home › XML › XML HttpRequest

XML HttpRequest

Web pages usually get XML from a server: a feed, a catalogue export, an API response. The browser gives you two tools for downloading it — the classic XMLHttpRequest object and the modern fetch() function. Despite its name, XMLHttpRequest can load any kind of data, but it has a built-in XML convenience you'll see below.

Note: ExcelTAD playgrounds run in a sandbox without a server to talk to, so the runnable demos below create the "server file" in the page itself with a Blob URL. The code that loads it is exactly what you would write against a real URL such as /data/books.xml.

Loading XML with fetch()

fetch() returns a promise for the response. Read the body as text, then parse it with DOMParser:

js
const response = await fetch('/data/books.xml');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const text = await response.text();
const doc = new DOMParser().parseFromString(text, 'application/xml');

Here is the same code running against a local stand-in file:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <ul id="out"></ul>
  <script type="module">
    // Pretend server file:
    const fileText = `<books>
      <book year="1949"><title>Nineteen Eighty-Four</title></book>
      <book year="1932"><title>Brave New World</title></book>
      <book year="1953"><title>Fahrenheit 451</title></book>
    </books>`;
    const url = URL.createObjectURL(new Blob([fileText], { type: 'application/xml' }));

    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const doc = new DOMParser().parseFromString(await response.text(), 'application/xml');

      for (const b of doc.getElementsByTagName('book')) {
        const li = document.createElement('li');
        li.textContent = `${b.querySelector('title').textContent} (${b.getAttribute('year')})`;
        document.getElementById('out').append(li);
      }
      console.log('Loaded', doc.getElementsByTagName('book').length, 'books');
    } catch (err) {
      console.log('Could not load the file:', err.message);
    }
  </script>
</body>
</html>

Loading XML with XMLHttpRequest

The older API is event-based. Its handy extra is responseXML: when the server sends an XML content type, the browser parses it for you.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const fileText = `<weather><city name="Oslo" temp="-3"/><city name="Cairo" temp="24"/></weather>`;
    const url = URL.createObjectURL(new Blob([fileText], { type: 'application/xml' }));

    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      if (xhr.status !== 200) { console.log('HTTP error', xhr.status); return; }
      const doc = xhr.responseXML;           // already a parsed XML Document
      for (const c of doc.getElementsByTagName('city')) {
        console.log(c.getAttribute('name') + ': ' + c.getAttribute('temp') + ' °C');
      }
    };
    xhr.onerror = function () { console.log('Network error'); };
    xhr.open('GET', url);
    xhr.send();
  </script>
</body>
</html>
Member Purpose
open(method, url) Prepare the request (GET, POST …)
send(body?) Send it; the body is used for POST/PUT
onload / onerror Called when the request finishes or fails
status HTTP status code, e.g. 200 or 404
responseText The body as a string
responseXML The body parsed as an XML Document (or null)
overrideMimeType('text/xml') Force XML parsing when the server sends the wrong type

fetch or XMLHttpRequest?

For new code, prefer fetch() with async/await: it is shorter, promise-based and works in service workers. XMLHttpRequest is still fully supported and you'll meet it in older code; it is also the simplest way to get upload progress events.

Same-origin rules

For security, a page may only read responses from its own origin (same scheme, host and port) unless the other server allows it with CORS headers (Access-Control-Allow-Origin). If you try to load https://other-site.com/feed.xml and that server doesn't send the header, the request fails with a network error — no matter which API you use. Common workarounds are to serve the file from your own site or to fetch it through your own server.

Tip: When opening HTML files straight from disk (file://), most browsers block fetch of neighbouring files. Use a local web server, such as the Vite dev server, while developing.

Test yourself

Which XMLHttpRequest property contains an already-parsed XML document?

  1. responseText
  2. responseXML
  3. response.xml()
  4. status

With fetch(), how do you turn the response into an XML document?

  1. await response.xml()
  2. await response.json()
  3. Read await response.text() and pass it to DOMParser
  4. fetch parses XML automatically

Why might loading XML from another website fail in the browser?

  1. XML can't travel over HTTP
  2. The other server doesn't allow it with CORS headers
  3. Browsers only load JSON
  4. The file is too small