Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Change Nodes in XML

Dom Change Nodes in XML

How to Change (Modify) Nodes in XML DOM

You can easily modify the content or attributes of existing XML nodes using the DOM API.


Ways to Change Nodes

  • Change the text content of an element.

  • Update or add attributes.

  • Replace or remove child nodes.


Example XML

<book id="101">  <title>Effective Java</title>  <author>Joshua Bloch</author></book>

JavaScript Example to Modify Nodes

// Assume xmlDoc is your parsed XML document// Get the <book> elementconst book = xmlDoc.getElementsByTagName("book")[0];// Change attribute 'id'book.setAttribute("id", "202");// Change the <title> textconst title = book.getElementsByTagName("title")[0];title.textContent = "Effective Java - 3rd Edition";// Change the <author> textconst author = book.getElementsByTagName("author")[0];author.textContent = "Joshua Bloch and Others";

Explanation

  • Use setAttribute() to modify attributes or add new ones.

  • Use .textContent to change the text inside an element.


Full Example with Display

<!DOCTYPE html><html><head><title>DOM Change Nodes in XML</title></head><body><h2>Modify XML Nodes</h2><button onclick="changeNodes()">Change Book Info</button><pre id="xmlOutput"></pre><script>const xmlString = `<book id="101">  <title>Effective Java</title>  <author>Joshua Bloch</author></book>`;const parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "text/xml");function displayXML() {  const serializer = new XMLSerializer();  const xmlStr = serializer.serializeToString(xmlDoc);  document.getElementById("xmlOutput").textContent = xmlStr;}function changeNodes() {  const book = xmlDoc.getElementsByTagName("book")[0];    // Change attribute  book.setAttribute("id", "202");    // Change title text  const title = book.getElementsByTagName("title")[0];  title.textContent = "Effective Java - 3rd Edition";    // Change author text  const author = book.getElementsByTagName("author")[0];  author.textContent = "Joshua Bloch and Others";  displayXML();}displayXML();</script></body></html>

Summary

OperationMethod/Property
Change attributeelement.setAttribute(name, value)
Change element textelement.textContent = "new text"

Want to learn how to remove nodes or replace nodes next?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql