DOM Parser
Parse and manipulate XML documents with JavaScript
🔍 What is DOM Parser?
DOM Parser converts XML text into a Document Object Model tree structure. This allows you to navigate, search, and modify XML data using JavaScript methods and properties.
// Parse XML string
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "text/xml");
DOM Parser Methods
The DOM Parser provides powerful methods to read and manipulate XML documents. These methods allow you to access elements, attributes, and text content, making it easy to extract and modify data programmatically.
Parse XML
Convert XML string to DOM
parseFromString(text, "text/xml")
Get Elements
Find elements by tag name
getElementsByTagName("book")
Get Attributes
Access element attributes
getAttribute("category")
Modify Content
Change element values
element.textContent = "New"
🔹 Basic XML Parsing
Parse an XML string and access its content:
// XML string
const xmlString = `
<?xml version="1.0"?>
<bookstore>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>10.99</price>
</book>
</bookstore>
`;
// Parse XML
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Access elements
const title = xmlDoc.getElementsByTagName("title")[0].textContent;
console.log(title); // Output: The Great Gatsby
Output:
The Great Gatsby
🔹 Getting Elements
Different ways to retrieve elements from XML:
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Get all books
const books = xmlDoc.getElementsByTagName("book");
console.log(books.length); // Number of books
// Get first book
const firstBook = books[0];
// Get child elements
const title = firstBook.getElementsByTagName("title")[0];
const author = firstBook.getElementsByTagName("author")[0];
console.log(title.textContent); // Book title
console.log(author.textContent); // Book author
🔹 Working with Attributes
Access and modify element attributes:
const xmlString = `
<book category="fiction" lang="en">
<title>Sample Book</title>
</book>
`;
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const book = xmlDoc.getElementsByTagName("book")[0];
// Get attribute value
const category = book.getAttribute("category");
console.log(category); // Output: fiction
// Check if attribute exists
if (book.hasAttribute("lang")) {
console.log("Language: " + book.getAttribute("lang"));
}
// Set attribute
book.setAttribute("year", "2024");
// Remove attribute
book.removeAttribute("lang");
Output:
fiction
Language: en
🔹 Navigating the DOM Tree
Navigate through parent, child, and sibling nodes:
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const book = xmlDoc.getElementsByTagName("book")[0];
// Get parent node
const parent = book.parentNode;
console.log(parent.nodeName); // bookstore
// Get child nodes
const children = book.childNodes;
// Get first child element
const firstChild = book.firstElementChild;
console.log(firstChild.nodeName); // title
// Get next sibling
const nextBook = book.nextElementSibling;
🔹 Modifying XML Content
Change element values and structure:
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Change text content
const title = xmlDoc.getElementsByTagName("title")[0];
title.textContent = "New Title";
// Create new element
const newElement = xmlDoc.createElement("publisher");
newElement.textContent = "ABC Publishing";
// Add to document
const book = xmlDoc.getElementsByTagName("book")[0];
book.appendChild(newElement);
// Remove element
const price = xmlDoc.getElementsByTagName("price")[0];
price.parentNode.removeChild(price);
🔹 Error Handling
Check for parsing errors in XML:
const xmlString = `
<book>
<title>Sample</title>
<!-- Missing closing tag -->
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Check for parse errors
const parseError = xmlDoc.getElementsByTagName("parsererror");
if (parseError.length > 0) {
console.log("XML Parsing Error!");
console.log(parseError[0].textContent);
} else {
console.log("XML parsed successfully");
}
🔹 Complete Example
Full example of parsing and displaying XML data:
const xmlString = `
<?xml version="1.0"?>
<library>
<book id="1">
<title>JavaScript Guide</title>
<author>John Smith</author>
</book>
<book id="2">
<title>XML Basics</title>
<author>Jane Doe</author>
</book>
</library>
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Get all books
const books = xmlDoc.getElementsByTagName("book");
// Loop through books
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;
console.log(`Book ${id}: ${title} by ${author}`);
}
Output:
Book 1: JavaScript Guide by John Smith
Book 2: XML Basics by Jane Doe
💡 Best Practices:
- Always check for parsing errors
- Use try-catch blocks for error handling
- Validate XML structure before parsing
- Cache frequently accessed elements
- Use specific selectors for better performance