Dom Accessing in XML
DOM Accessing in XML — How to Access XML Nodes Using DOM
When working with XML, the DOM (Document Object Model) lets you access elements, attributes, and text inside the XML document in a tree-like structure. Here’s how to access XML data using DOM in JavaScript.
Example XML (books.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>Accessing XML Nodes with JavaScript DOM
Step 1: Load and Parse XML (Assuming XML is already loaded as xmlDoc)
// Access all <book> elementsconst books = xmlDoc.getElementsByTagName("book");// Loop through each bookfor (let i = 0; i < books.length; i++) { // Access attribute 'id' const bookId = books[i].getAttribute("id"); // Access child elements <title> and <author> const title = books[i].getElementsByTagName("title")[0].textContent; const author = books[i].getElementsByTagName("author")[0].textContent; console.log(`Book ID: ${bookId}, Title: ${title}, Author: ${author}`);}Important DOM Methods for XML Access
| Method | Description |
|---|---|
getElementsByTagName(name) | Returns a list of elements with the given tag name |
getAttribute(name) | Returns the value of an attribute |
childNodes | Returns all child nodes of an element |
textContent | Retrieves or sets the text content of a node |
firstChild, lastChild | Access first or last child node |
Full Working Example: Load XML and Access DOM
<!DOCTYPE html><html><head><title>Access XML DOM Example</title></head><body><h2>Books List</h2><div id="output"></div><script>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>`;// Parse XML string into XML DOMconst parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "text/xml");// Access all book elementsconst books = xmlDoc.getElementsByTagName("book");let html = "<ul>";for (let i = 0; i < books.length; i++) { const id = books[i].getAttribute("id"); const title = books[i].getElementsByTagName("title")[0].textContent; const author = books[i].getElementsByTagName("author")[0].textContent; html += `<li><strong>${title}</strong> by ${author} (ID: ${id})</li>`;}html += "</ul>";document.getElementById("output").innerHTML = html;</script></body></html>Summary
Use
getElementsByTagNameto select elements.Use
getAttributeto access element attributes.Use
textContentto get the text inside an element.Traverse child nodes if needed for complex XML.
Want examples with modifying or adding nodes in XML DOM?