XML DOM

Navigating and manipulating XML documents

🌳 What is XML DOM?

The XML Document Object Model (DOM) is a programming interface that represents XML documents as a tree structure. It allows you to navigate, access, modify, and manipulate XML elements and attributes programmatically.


// Access XML DOM
const xmlDoc = parser.parseFromString(xml, "text/xml");
const element = xmlDoc.getElementsByTagName("item")[0];
                                    

Purpose:

DOM provides methods to read, modify, and navigate XML document structure.

Key DOM Concepts

📄

Nodes

Everything is a node in DOM

element.childNodes
🔍

Navigate

Move through the tree structure

node.parentNode
node.firstChild
✏️

Modify

Change element content and attributes

element.textContent = "New"
element.setAttribute("id", "1")

Create

Add new elements and nodes

xmlDoc.createElement("item")
parent.appendChild(child)

🔹 DOM Tree Structure

XML documents are represented as a hierarchical tree of nodes. Understanding this structure is essential for navigating and manipulating XML data.

<?xml version="1.0"?>
<library>
    <book id="B001">
        <title>XML Guide</title>
        <author>John Doe</author>
    </book>
</library>

Tree Structure:

Document
  └─ library (root element)
      └─ book (element, id="B001")
          ├─ title (element)
          │   └─ "XML Guide" (text node)
          └─ author (element)
              └─ "John Doe" (text node)
                

🔹 Accessing DOM Elements

The DOM provides multiple methods to access elements. Choose the method that best fits your needs for efficient XML navigation.

const xmlString = `
<catalog>
    <product id="P001" category="electronics">
        <name>Laptop</name>
        <price>999.99</price>
    </product>
    <product id="P002" category="books">
        <name>XML Handbook</name>
        <price>29.99</price>
    </product>
</catalog>`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");

// Get elements by tag name
const products = xmlDoc.getElementsByTagName("product");
console.log("Total products: " + products.length);

// Get root element
const root = xmlDoc.documentElement;
console.log("Root: " + root.nodeName);

// Get first product
const firstProduct = products[0];
console.log("First product ID: " + firstProduct.getAttribute("id"));

// Get product name
const name = firstProduct.getElementsByTagName("name")[0].textContent;
console.log("Product name: " + name);

// Get all prices
const prices = xmlDoc.getElementsByTagName("price");
for (let i = 0; i < prices.length; i++) {
    console.log("Price " + (i+1) + ": $" + prices[i].textContent);
}

Console Output:

Total products: 2

Root: catalog

First product ID: P001

Product name: Laptop

Price 1: $999.99

Price 2: $29.99

🔹 Navigating the DOM Tree

DOM provides properties to navigate between parent, child, and sibling nodes. This allows you to traverse the entire XML structure.

const xmlString = `
<family>
    <parent>John</parent>
    <child>Alice</child>
    <child>Bob</child>
</family>`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");

const root = xmlDoc.documentElement;
console.log("Root: " + root.nodeName);

// Get first child element
const firstChild = root.firstElementChild;
console.log("First child: " + firstChild.nodeName + " = " + firstChild.textContent);

// Get last child element
const lastChild = root.lastElementChild;
console.log("Last child: " + lastChild.nodeName + " = " + lastChild.textContent);

// Get all children
const children = root.children;
console.log("Number of children: " + children.length);

// Navigate siblings
const parent = root.firstElementChild;
const nextSibling = parent.nextElementSibling;
console.log("Next sibling: " + nextSibling.nodeName + " = " + nextSibling.textContent);

// Get parent node
const childElement = xmlDoc.getElementsByTagName("child")[0];
const parentNode = childElement.parentNode;
console.log("Parent of child: " + parentNode.nodeName);

Console Output:

Root: family

First child: parent = John

Last child: child = Bob

Number of children: 3

Next sibling: child = Alice

Parent of child: family

🔹 Modifying DOM Elements

The DOM allows you to change element content, attributes, and structure dynamically. This is useful for updating XML data programmatically.

const xmlString = `
<product id="P001">
    <name>Laptop</name>
    <price>999.99</price>
</product>`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");

const product = xmlDoc.getElementsByTagName("product")[0];

// Change attribute
product.setAttribute("id", "P999");
product.setAttribute("status", "updated");
console.log("New ID: " + product.getAttribute("id"));

// Change element text content
const name = product.getElementsByTagName("name")[0];
name.textContent = "Gaming Laptop";
console.log("New name: " + name.textContent);

// Change price
const price = product.getElementsByTagName("price")[0];
price.textContent = "1299.99";
console.log("New price: $" + price.textContent);

// Serialize back to string
const serializer = new XMLSerializer();
const updatedXML = serializer.serializeToString(xmlDoc);
console.log("\nUpdated XML:");
console.log(updatedXML);

Result:

New ID: P999

New name: Gaming Laptop

New price: $1299.99

<product id="P999" status="updated">
  <name>Gaming Laptop</name>
  <price>1299.99</price>
</product>

🔹 Creating and Adding Elements

You can create new elements and add them to the XML document using DOM methods. This is essential for building XML dynamically.

const xmlString = "<catalog></catalog>";
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");

const catalog = xmlDoc.documentElement;

// Create new product element
const product = xmlDoc.createElement("product");
product.setAttribute("id", "P003");

// Create and add name element
const name = xmlDoc.createElement("name");
name.textContent = "Wireless Mouse";
product.appendChild(name);

// Create and add price element
const price = xmlDoc.createElement("price");
price.textContent = "24.99";
product.appendChild(price);

// Create and add category element
const category = xmlDoc.createElement("category");
category.textContent = "Accessories";
product.appendChild(category);

// Add product to catalog
catalog.appendChild(product);

// Serialize to string
const serializer = new XMLSerializer();
const finalXML = serializer.serializeToString(xmlDoc);
console.log(finalXML);

Generated XML:

<catalog>
  <product id="P003">
    <name>Wireless Mouse</name>
    <price>24.99</price>
    <category>Accessories</category>
  </product>
</catalog>

🔹 Removing DOM Elements

The DOM also allows you to remove elements and attributes from XML documents when needed.

const xmlString = `
<library>
    <book id="B001" status="old">
        <title>Old Book</title>
        <author>Unknown</author>
    </book>
    <book id="B002">
        <title>New Book</title>
        <author>John Smith</author>
    </book>
</library>`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");

const library = xmlDoc.documentElement;
const books = xmlDoc.getElementsByTagName("book");

// Remove attribute
const firstBook = books[0];
firstBook.removeAttribute("status");
console.log("Removed 'status' attribute");

// Remove child element
const author = firstBook.getElementsByTagName("author")[0];
firstBook.removeChild(author);
console.log("Removed 'author' element");

// Remove entire book element
library.removeChild(firstBook);
console.log("Removed first book");

// Serialize result
const serializer = new XMLSerializer();
const result = serializer.serializeToString(xmlDoc);
console.log("\nFinal XML:");
console.log(result);

Result:

<library>
  <book id="B002">
    <title>New Book</title>
    <author>John Smith</author>
  </book>
</library>

🧠 Test Your Knowledge

What does DOM stand for in XML?