Chapter 32: XML DOM
1. What is XML DOM? (The clearest explanation)
DOM = Document Object Model
When we talk about XML DOM, we mean:
The XML document is loaded into memory and turned into a tree of objects (like a family tree or folder structure) that JavaScript can easily navigate, read, change, add to, or remove from — just like working with HTML elements.
Think of it like this:
- The XML file/text is like a folded paper document
- The XML parser opens it completely
- Every tag becomes a node (an object)
- These nodes are connected in a tree (parent–child relationships)
- JavaScript gets this tree and can walk around it freely
Analogy most people understand immediately:
Imagine the XML is a family photo album:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<family> <parent id="dad"> <name>John</name> <age>42</age> </parent> <parent id="mom"> <name>Mary</name> <age>40</age> </parent> <child> <name>Anna</name> <age>12</age> </child> </family> |
After parsing to DOM:
- There is one root node (<family>)
- It has three children (<parent>, <parent>, <child>)
- Each <parent> has two children (<name>, <age>)
- You can ask questions like:
- “Who is the first parent’s name?”
- “Give me all names”
- “Change Anna’s age to 13”
- “Add a new child”
That’s exactly what the XML DOM lets you do.
2. How to create an XML DOM in JavaScript (two main ways)
Way 1: From a string (most common in AJAX / modern code)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const xmlString = ` <?xml version="1.0" encoding="UTF-8"?> <book id="B101"> <title>Atomic Habits</title> <author>James Clear</author> <year>2018</year> <price currency="INR">499.00</price> </book> `; // Create DOM parser const parser = new DOMParser(); // Parse the string into a Document object const xmlDoc = parser.parseFromString(xmlString, "application/xml"); // Check if parsing succeeded const parseError = xmlDoc.querySelector("parsererror"); if (parseError) { console.error("XML parsing failed:", parseError.textContent); } else { console.log("XML parsed successfully!"); } |
Way 2: From a server response (classic AJAX style)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const xhr = new XMLHttpRequest(); xhr.open("GET", "book.xml", true); xhr.onload = function () { if (xhr.status === 200) { const xmlDoc = xhr.responseXML; // ← already parsed DOM! if (xmlDoc) { console.log("Title:", xmlDoc.querySelector("title").textContent); } else { console.error("Not valid XML"); } } }; xhr.send(); |
3. The XML DOM Tree – Visualized
For this XML:
|
0 1 2 3 4 5 6 7 8 9 10 |
<book id="B101" lang="en"> <title>Atomic Habits</title> <author>James Clear</author> <price currency="INR">499.00</price> </book> |
The DOM tree looks like this:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Document └── Element: book ├── Attribute: id = "B101" ├── Attribute: lang = "en" ├── Element: title │ └── Text: "Atomic Habits" ├── Element: author │ └── Text: "James Clear" └── Element: price ├── Attribute: currency = "INR" └── Text: "499.00" |
Every tag → Element node Every piece of text → Text node Every attribute → Attr node
4. Most Important Ways to Work with the XML DOM
a) Getting the root element
|
0 1 2 3 4 5 6 |
const root = xmlDoc.documentElement; // <book> in our example |
b) Finding elements (several useful methods)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// 1. By tag name (returns NodeList) const titles = xmlDoc.getElementsByTagName("title"); console.log(titles[0].textContent); // "Atomic Habits" // 2. First match (modern & clean) const author = xmlDoc.querySelector("author"); console.log(author.textContent); // "James Clear" // 3. All matches const prices = xmlDoc.querySelectorAll("price"); prices.forEach(p => { console.log("Price:", p.textContent, "Currency:", p.getAttribute("currency")); }); // 4. From a specific starting point const book = xmlDoc.querySelector("book"); const title = book.querySelector("title"); |
c) Reading attributes
|
0 1 2 3 4 5 6 7 8 |
const book = xmlDoc.documentElement; console.log("Book ID:", book.getAttribute("id")); // "B101" console.log("Language:", book.getAttribute("lang")); // "en" |
d) Changing values (the DOM is live!)
|
0 1 2 3 4 5 6 7 8 |
const price = xmlDoc.querySelector("price"); price.textContent = "549.00"; // Change text price.setAttribute("currency", "USD"); // Change attribute |
e) Creating new elements & adding them
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Create new element const newTag = xmlDoc.createElement("discount"); newTag.textContent = "10%"; // Add it somewhere const book = xmlDoc.documentElement; book.appendChild(newTag); // Or insert at specific position book.insertBefore(newTag, book.firstElementChild); |
f) Removing elements
|
0 1 2 3 4 5 6 7 8 9 |
const oldPrice = xmlDoc.querySelector("price"); if (oldPrice) { oldPrice.parentNode.removeChild(oldPrice); } |
5. Full Realistic Example – Load XML via AJAX & Display It
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AJAX + XML DOM – Real Example</title> <style> body { font-family: Arial; margin: 40px; } button { padding: 12px 24px; font-size: 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; } #output { margin-top: 30px; padding: 25px; background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; } </style> </head> <body> <h2>AJAX + XML DOM – Product Catalog</h2> <button onclick="loadProducts()">Load Products from XML</button> <div id="output">Click the button to load catalog...</div> <script> async function loadProducts() { const output = document.getElementById("output"); output.innerHTML = "Loading catalog..."; try { const response = await fetch("products.xml"); if (!response.ok) { throw new Error(`HTTP {response.status}`); } const xmlText = await response.text(); // Parse XML string into DOM const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml"); // Check for parse error if (xmlDoc.querySelector("parsererror")) { throw new Error("Invalid XML format"); } // Now work with the DOM const products = xmlDoc.querySelectorAll("product"); let html = "<h3>Product Catalog</h3><ul>"; products.forEach(product => { const name = product.querySelector("name").textContent; const price = product.querySelector("price").textContent; const curr = product.querySelector("price").getAttribute("currency") || "USD"; html += `<li><strong>${name}</strong> – ${curr} ${price}</li>`; }); html += "</ul>"; output.innerHTML = html; } catch (err) { output.innerHTML = `<strong style="color:red">Error:</strong> ${err.message}`; } } </script> </body> </html> |
File: products.xml (put in same folder)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="UTF-8"?> <catalog> <product> <name>Wireless Mouse</name> <price currency="INR">1499.00</price> </product> <product> <name>Bluetooth Speaker</name> <price currency="INR">3499.00</price> </product> <product> <name>Mechanical Keyboard</name> <price currency="INR">3999.00</price> </product> </catalog> |
Summary – XML DOM in JavaScript – Cheat Sheet
| Task | Code example |
|---|---|
| Parse string → DOM | parser.parseFromString(xmlString, “application/xml”) |
| Get root element | xmlDoc.documentElement |
| Find first element | xmlDoc.querySelector(“title”) |
| Find all elements | xmlDoc.querySelectorAll(“price”) |
| Get text content | element.textContent |
| Get attribute | element.getAttribute(“currency”) |
| Change text | element.textContent = “New value” |
| Change attribute | element.setAttribute(“currency”, “USD”) |
| Add new child | parent.appendChild(xmlDoc.createElement(“tag”)) |
| Remove element | element.parentNode.removeChild(element) |
Would you like to go deeper into any part?
- How to handle namespaces in XML DOM (very common in real data)
- Creating XML from scratch and sending it via AJAX
- Walking the tree manually (parentNode, childNodes, nextSibling…)
- Common mistakes & how to debug XML parsing
- Modern alternative — parsing XML with DOMParser + fetch
- Real example from SOAP response, RSS feed, configuration file
Just tell me what you want to practice or understand more deeply! 😊
