3️⃣ 🧱 XML DOM (Document Object Model)
Estimated reading: 4 minutes 27 views

💡 XML DOM Examples – Practical JavaScript Snippets for XML DOM Manipulation

🧲 Introduction – Why Learn XML DOM Examples?

Knowing XML DOM methods is essential, but seeing them in action is where the learning really clicks. These hands-on examples cover real-world scenarios like accessing, modifying, adding, removing, and cloning XML nodes. Whether you’re building a dashboard, a feed reader, or a config editor, these examples provide clear and functional reference.

🎯 In this guide, you’ll explore:

  • Realistic XML DOM tasks with working JavaScript examples
  • Use of methods like getElementsByTagName(), setAttribute(), appendChild()
  • Examples for reading, writing, and manipulating XML

📄 Sample XML Document

<library>
  <book id="001">
    <title>XML Basics</title>
    <author>Jane Doe</author>
  </book>
</library>

🧾 Example 1 – Access Element and Text Value

var book = xmlDoc.getElementsByTagName("book")[0];
var title = book.getElementsByTagName("title")[0].textContent;
console.log("Title:", title); // Output: XML Basics

✅ Reads the content inside <title>.


✏️ Example 2 – Modify Element Content

var titleNode = xmlDoc.getElementsByTagName("title")[0];
titleNode.textContent = "Advanced XML";

✅ Changes <title> content from “XML Basics” to “Advanced XML”.


🏷️ Example 3 – Modify Attribute Value

var book = xmlDoc.getElementsByTagName("book")[0];
book.setAttribute("id", "002");

✅ Changes the id of the <book> element to 002.


➕ Example 4 – Add New Node

var newBook = xmlDoc.createElement("book");
newBook.setAttribute("id", "003");

var title = xmlDoc.createElement("title");
title.textContent = "Learn XML";

var author = xmlDoc.createElement("author");
author.textContent = "John Smith";

newBook.appendChild(title);
newBook.appendChild(author);

var library = xmlDoc.getElementsByTagName("library")[0];
library.appendChild(newBook);

✅ Dynamically adds a new <book> to <library>.


❌ Example 5 – Remove an Existing Node

var price = xmlDoc.getElementsByTagName("price")[0];
price.parentNode.removeChild(price);

✅ Deletes the <price> node from the XML structure.


🔁 Example 6 – Replace a Node

var oldAuthor = xmlDoc.getElementsByTagName("author")[0];
var newAuthor = xmlDoc.createElement("author");
newAuthor.textContent = "Revised Author";

oldAuthor.parentNode.replaceChild(newAuthor, oldAuthor);

✅ Replaces the current <author> tag with a new one.


🧬 Example 7 – Clone a Node and Append It

var book = xmlDoc.getElementsByTagName("book")[0];
var clone = book.cloneNode(true);
clone.setAttribute("id", "004");

var library = xmlDoc.getElementsByTagName("library")[0];
library.appendChild(clone);

✅ Clones the first <book> and inserts it into the DOM as a new book.


🧭 Example 8 – Traverse and Print All Titles

var books = xmlDoc.getElementsByTagName("book");
for (let i = 0; i < books.length; i++) {
  let title = books[i].getElementsByTagName("title")[0].textContent;
  console.log("Book " + (i + 1) + ": " + title);
}

✅ Loops through every book and prints its title.


🧰 Useful XML DOM Methods Recap

MethodDescription
getElementsByTagName()Find elements by tag name
setAttribute()Set or update an attribute
createElement()Create a new XML tag
createTextNode()Create a text node
appendChild()Append node to a parent
removeChild()Remove a node from parent
replaceChild()Replace one node with another
cloneNode(true)Deep copy a node with all children

✅ Best Practices for XML DOM Manipulation

  • ✔️ Normalize XML after heavy node edits using .normalize()
  • ✔️ Always check if a node exists before modifying or deleting
  • ✔️ Use textContent over nodeValue for elements
  • ✔️ Use loops to safely modify or clone multiple nodes
  • ❌ Don’t directly manipulate XML as strings—use DOM methods for safety

📌 Summary – Recap & Next Steps

These XML DOM examples offer a full toolkit for working with XML in JavaScript. You now know how to read, write, update, and structure XML programmatically—paving the way for XML-driven interfaces, editors, and dynamic APIs.

🔍 Key Takeaways:

  • Access elements using getElementsByTagName()
  • Modify text and attributes with textContent and setAttribute()
  • Add, remove, and replace nodes using DOM methods
  • Clone nodes to replicate structures dynamically

⚙️ Real-world relevance: These examples apply to CMS systems, config UIs, document editors, and any system using XML for structured data.


❓ FAQs – XML DOM Examples

❓ Can I use these examples with external XML files?
✅ Yes. Load the file with XMLHttpRequest or fetch() and use responseXML.

❓ What if my XML has whitespace-only text nodes?
✅ Filter nodes using nodeType === 1 to ignore text/whitespace nodes.

❓ Can I use DOMParser to create XML from a string?
✅ Yes. Use new DOMParser().parseFromString(xmlString, "text/xml").

❓ Can I update an XML document and save it?
✅ On the client side, you can update it in memory. To save, send it to the server via AJAX.

❓ Is XML DOM supported in all browsers?
✅ Yes. It’s a W3C standard and works across all modern browsers.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

XML DOM Examples

Or Copy Link

CONTENTS
Scroll to Top