Dom Traversing in XML
DOM Traversing in XML
DOM Traversing means navigating through the nodes of an XML document tree to access or manipulate elements, attributes, text, and other node types.
Key Concepts for Traversing XML DOM
Each node in the DOM tree has relationships:
| Relationship | Description |
|---|---|
| parentNode | The node that contains the current node |
| childNodes | A collection of all child nodes |
| firstChild | The first child node |
| lastChild | The last child node |
| previousSibling | The node immediately before the current one |
| nextSibling | The node immediately after the current one |
Common Properties/Methods for Traversing
| Property/Method | Description |
|---|---|
node.parentNode | Gets the parent of the current node |
node.childNodes | Gets all child nodes as a NodeList |
node.firstChild | Gets the first child node |
node.lastChild | Gets the last child node |
node.previousSibling | Gets the previous sibling node |
node.nextSibling | Gets the next sibling node |
node.firstElementChild | First child element (ignores text/comments) |
node.lastElementChild | Last child element |
node.children | Collection of child elements (ignores text nodes) |
Example XML
<library> <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> </book> <book id="102"> <title>Clean Code</title> <author>Robert C. Martin</author> </book></library>Traversing Example in JavaScript
const parser = new DOMParser();const xmlString = ` <library> <book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author> </book> <book id="102"> <title>Clean Code</title> <author>Robert C. Martin</author> </book> </library>`;const xmlDoc = parser.parseFromString(xmlString, "text/xml");// Access <library> elementconst library = xmlDoc.getElementsByTagName("library")[0];// Access first <book> element (ignoring text nodes)const firstBook = library.firstElementChild;console.log(firstBook.nodeName); // "book"// Access next sibling (second <book>)const secondBook = firstBook.nextElementSibling;console.log(secondBook.getAttribute("id")); // "102"// Access children of first bookconst title = firstBook.getElementsByTagName("title")[0].textContent;const author = firstBook.getElementsByTagName("author")[0].textContent;console.log(`Title: ${title}, Author: ${author}`);// Traversing child nodes (including text nodes)for (let i = 0; i < firstBook.childNodes.length; i++) { const node = firstBook.childNodes[i]; console.log(`${node.nodeName} - type: ${node.nodeType}`);}Notes:
Use
.firstElementChildand.nextElementSiblingto skip text nodes (like whitespace)..childNodesincludes all nodes: elements, text, comments, etc.Traversal is essential for reading or modifying parts of an XML document dynamically.
If you want, I can create examples for recursive traversal or searching nodes by criteria!