XML DOM Introduction
The DOM (Document Object Model) is a standard, language-neutral way to represent a document as a tree of objects that a program can read and change. The same DOM API that JavaScript uses for HTML pages also works on XML documents — so once you have parsed XML with DOMParser, you can explore it with methods you may already know, like getElementsByTagName, getAttribute and appendChild.
What the DOM gives you
| Task | DOM feature |
|---|---|
| Load XML | DOMParser, XMLHttpRequest.responseXML |
| Find nodes | getElementsByTagName, querySelector, XPath evaluate |
| Read values | textContent, nodeValue, getAttribute |
| Move around | parentNode, childNodes, nextSibling, firstElementChild … |
| Change things | textContent = …, setAttribute, removeChild, replaceChild |
| Build new nodes | createElement, createTextNode, cloneNode |
| Save back to text | XMLSerializer |
The rest of this section takes these one at a time.
The sample document
Most lessons in this section use the same small library catalogue, so you can concentrate on the API:
<library>
<book id="b1" genre="fantasy">
<title lang="en">The Hobbit</title>
<author>J. R. R. Tolkien</author>
<year>1937</year>
<price>8.99</price>
</book>
<book id="b2" genre="science">
<title lang="en">A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
<price>12.50</price>
</book>
<book id="b3" genre="fantasy">
<title lang="es">Cien años de soledad</title>
<author>Gabriel García Márquez</author>
<year>1967</year>
<price>10.00</price>
</book>
</library>A first DOM program
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
const xml = `<library>
<book id="b1" genre="fantasy"><title lang="en">The Hobbit</title><author>J. R. R. Tolkien</author><year>1937</year><price>8.99</price></book>
<book id="b2" genre="science"><title lang="en">A Brief History of Time</title><author>Stephen Hawking</author><year>1988</year><price>12.50</price></book>
<book id="b3" genre="fantasy"><title lang="es">Cien años de soledad</title><author>Gabriel García Márquez</author><year>1967</year><price>10.00</price></book>
</library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const firstTitle = xmlDoc.getElementsByTagName('title')[0];
document.getElementById('out').textContent = 'First title: ' + firstTitle.textContent;
console.log('Root:', xmlDoc.documentElement.nodeName);
console.log('Books:', xmlDoc.getElementsByTagName('book').length);
console.log('Language of first title:', firstTitle.getAttribute('lang'));
</script>
</body>
</html>Two documents are involved here: document is the HTML page, xmlDoc is the XML data. You read from one and write into the other. Keeping the variable names distinct avoids a lot of confusion.
XML DOM vs HTML DOM
It is the same API, but a few things behave differently with XML:
| HTML document | XML document | |
|---|---|---|
| Tag name case | tagName is upper-case ("P") |
Exactly as written ("book") |
| Name matching | Case-insensitive | Case-sensitive |
Shortcuts like document.body, .innerText, .style, .className |
Available | Not available (plain Element objects) |
id lookup |
getElementById uses id attributes |
Works only for attributes declared as IDs; use querySelector('[id="b1"]') instead |
| White space between tags | Usually ignored in layout | Kept as text nodes |
<!DOCTYPE html>
<html>
<body>
<script>
const xmlDoc = new DOMParser().parseFromString('<Library><Book id="b1"/></Library>', 'application/xml');
console.log('tagName:', xmlDoc.documentElement.tagName);
console.log('lower-case search finds:', xmlDoc.getElementsByTagName('book').length);
console.log('exact search finds:', xmlDoc.getElementsByTagName('Book').length);
console.log('querySelector by id:', xmlDoc.querySelector('[id="b1"]').tagName);
console.log('HTML tagName for comparison:', document.createElement('p').tagName);
</script>
</body>
</html>A W3C standard
The DOM is defined by the W3C/WHATWG and implemented in every browser and in libraries for Java, Python (xml.dom.minidom), C#, PHP and others. The method names you learn here are nearly identical everywhere, which makes the DOM a very portable skill.
Tip: Modern code often uses CSS selectors (
querySelector,querySelectorAll) on XML documents too. They work as long as the names don't contain namespace prefixes; for namespaced documents use the…NSmethods or XPath.
Test yourself
In the XML DOM, what does xmlDoc.documentElement return?
- The XML declaration
- The root element
- The first text node
- The HTML page
What is tagName of <book> in an XML document?
BOOKbookBook#element