Skip to content

XML DOM

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the document’s structure as a tree of objects, allowing programs to access and manipulate its content, structure, and style.

Specifically for XML, the DOM provides a standard way to:

  • Parse an XML document into a tree structure in memory.
  • Navigate this tree (e.g., find elements, move between parent, child, and sibling nodes).
  • Access element content (text) and attributes.
  • Modify the tree (add, change, or delete elements, attributes, and text).
  • Serialize the modified tree back into an XML string.

Each part of the XML document (the document itself, elements, attributes, text content) is represented as a ‘node’ in the DOM tree.

Understanding the DOM is essential for programmatically working with XML data, especially in web browsers using JavaScript.

The HTML DOM is similar but specifically tailored for HTML documents. It provides convenient properties and methods reflecting HTML structure (like document.getElementById, element.innerHTML).

The XML DOM is more generic but follows the same core principles of a tree structure and node manipulation.

Loading and Parsing XML from a File (Modern JavaScript)

Section titled “Loading and Parsing XML from a File (Modern JavaScript)”

This example uses the modern fetch API to retrieve an XML file (‘note.xml’) and the DOMParser to parse it into an XML DOM object. It then extracts information using standard DOM methods.

<h1>Internal Note</h1>
<div>
**To:** <span id="to"></span><br/>
**From:** <span id="from"></span><br/>
**Message:** <span id="message"></span>
</div>
async function loadNote() {
try {
const response = await fetch('note.xml');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Check for parsing errors
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
console.error('Error parsing XML:', parseError);
throw new Error('Failed to parse XML');
}
// Access data using DOM methods
const to = xmlDoc.querySelector('to')?.textContent || 'N/A';
const from = xmlDoc.querySelector('from')?.textContent || 'N/A';
const message = xmlDoc.querySelector('body')?.textContent || 'N/A';
document.getElementById('to').textContent = to;
document.getElementById('from').textContent = from;
document.getElementById('message').textContent = message;
} catch (error) {
console.error('Could not load or parse XML:', error);
document.getElementById('message').textContent = 'Error loading note.';
}
}
// Call the function when the page loads or on an event
loadNote();

Key points:

  • fetch('note.xml'): Asynchronously retrieves the file.
  • response.text(): Gets the file content as a string.
  • new DOMParser(): Creates a parser object.
  • parser.parseFromString(xmlText, "application/xml"): Parses the string into an XML DOM.
  • xmlDoc.querySelector(): A modern way to select elements using CSS selectors (also works on XML DOM). ?.textContent safely accesses text content.
  • Error handling is included for network and parsing issues.

This example demonstrates parsing an XML string directly using DOMParser.

// Assume the same HTML structure as the previous example
const xmlString = `
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`;
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
// Check for parsing errors
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
console.error('Error parsing XML:', parseError);
throw new Error('Failed to parse XML');
}
// Access data using DOM methods (e.g., querySelector or getElementsByTagName)
const to = xmlDoc.getElementsByTagName('to')[0]?.textContent || 'N/A';
const from = xmlDoc.getElementsByTagName('from')[0]?.textContent || 'N/A';
const message = xmlDoc.getElementsByTagName('body')[0]?.textContent || 'N/A';
document.getElementById('to').textContent = to;
document.getElementById('from').textContent = from;
document.getElementById('message').textContent = message;
} catch (error) {
console.error('Could not parse XML string:', error);
document.getElementById('message').textContent = 'Error parsing note data.';
}

Here, getElementsByTagName is also shown as an alternative way to select elements. It returns an HTMLCollection (a list), so you typically access the first item [0]. Using querySelector is often more convenient.

Important: Accessing childNodes[0].nodeValue (as seen in older examples) can be fragile, as it depends on the exact node structure (including whitespace nodes). Using textContent is generally more robust for getting the combined text content of an element.