TExcelTAD
Home › XML › XML Parser

XML Parser

A parser reads XML text and turns it into a structure a program can work with. Every modern browser has a built-in XML parser, available to JavaScript as DOMParser. It produces an XML Document object — the same kind of tree you use to manipulate HTML pages, which is why the methods will feel familiar.

Parsing a string

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const text = `<planet name="Mars">
      <moons>2</moons>
      <dayLength unit="hours">24.6</dayLength>
    </planet>`;

    const parser = new DOMParser();
    const doc = parser.parseFromString(text, 'application/xml');

    const root = doc.documentElement;
    console.log('Root element:', root.tagName);
    console.log('Name attribute:', root.getAttribute('name'));
    console.log('Moons:', doc.querySelector('moons').textContent);
    const day = doc.querySelector('dayLength');
    console.log('Day:', day.textContent, day.getAttribute('unit'));
  </script>
</body>
</html>

parseFromString(text, mimeType) takes two arguments:

MIME type Result
application/xml or text/xml Strict XML parsing — the right choice for XML data
image/svg+xml XML parsing, SVG elements recognised
application/xhtml+xml XML parsing, XHTML elements recognised
text/html Forgiving HTML parser — never use it for XML data

Detecting parse errors

DOMParser doesn't throw an exception when the XML is broken. Instead it returns a document containing a <parsererror> element with a message. Always check for it:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    function parseXml(text) {
      const doc = new DOMParser().parseFromString(text, 'application/xml');
      const err = doc.querySelector('parsererror');
      if (err) {
        // Chrome/Safari put the message in a <div>; Firefox puts it directly in parsererror
        const msg = (err.querySelector('div') ?? err).textContent.trim().split('\n')[0];
        throw new Error('Invalid XML: ' + msg);
      }
      return doc;
    }

    for (const sample of ['<a><b>ok</b></a>', '<a><b>broken</a>', '<a x=1/>']) {
      try {
        const doc = parseXml(sample);
        console.log('OK  ', sample, '→ root', doc.documentElement.tagName);
      } catch (e) {
        console.log('FAIL', sample, '→', e.message);
      }
    }
  </script>
</body>
</html>

Note: The exact wording of the error message differs between Chrome, Firefox and Safari, so test for the presence of parsererror rather than matching the text.

Why not use text/html?

The HTML parser is designed to fix mistakes, and it lower-cases tag names and treats some names specially. Feeding it XML produces surprising results:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const text = '<Order><Item>Pen</Item><table>2</table></Order>';

    const asXml  = new DOMParser().parseFromString(text, 'application/xml');
    const asHtml = new DOMParser().parseFromString(text, 'text/html');

    console.log('XML parser root :', asXml.documentElement.tagName);
    console.log('XML finds <Item>:', asXml.getElementsByTagName('Item').length);
    console.log('HTML parser root:', asHtml.documentElement.tagName);
    console.log('HTML body holds :', asHtml.body.innerHTML);
  </script>
</body>
</html>

The HTML parser wraps everything in <html><body>, changes the case of the names, and moves the <table> out of place because tables have special rules in HTML.

Parsing in other environments

Every major platform has an XML parser. The ideas — parse, get a tree, navigate it — are the same everywhere:

Platform Typical API
Browser JavaScript DOMParser, XMLSerializer, document.evaluate
Node.js npm packages such as @xmldom/xmldom, fast-xml-parser, sax
Python xml.etree.ElementTree, lxml
Java javax.xml.parsers (DOM, SAX), StAX
C# / .NET XDocument (LINQ to XML), XmlReader

DOM vs streaming parsers

DOMParser builds the whole tree in memory. That's convenient, but for a 2 GB data dump it would use far too much RAM. Streaming parsers (SAX, StAX, XmlReader) instead read the file piece by piece and report events — "start of <item>", "some text", "end of <item>" — so memory use stays small. Use a DOM parser for normal documents and a streaming parser for huge ones.

Tip: Never build XML by gluing strings together with user input — a stray < or & breaks the document. Build a DOM and serialise it, or escape values properly (see the DOM Serializing lesson).

Test yourself

What does DOMParser do when the XML is not well-formed?

  1. Throws a SyntaxError
  2. Returns null
  3. Returns a document containing a parsererror element
  4. Fixes the mistakes silently

Which MIME type should you pass to parse XML data strictly?

  1. text/html
  2. application/xml
  3. text/plain
  4. application/json

When is a streaming (SAX-style) parser a better choice than a DOM parser?

  1. For very large files that shouldn't be loaded into memory at once
  2. For tiny configuration files
  3. When you need to change the document
  4. Never — DOM parsers are always faster