XML DOM Replace Nodes

To replace a specified node, we can use the replaceChild() method, while text in a text node can be replaced by the nodeValue property.

Replace an Element Node:

Replacing a node is possible with the replaceChild() method.

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
    Author 3
    Author 4
    2005
    350.00
  


Example:





Explanation:

In the above example, we are replacing the first <book> element, for which we are loading “books.xml” in the xmlDoc. After creating a new element node <book>, a new element node <title>, and a new text node with the text “A Notebook”, we will append the new text node to the new element node <title>, the new element node <title> to the new element node <book> and will replace the first <book> element node with the new <book> element node.

Replace Data In a Text Node:

We can replace data in a text node using the replaceData() method having three parameters:

  • offset – It is used to specify the value to begin replacing characters. Its value starts at zero.
  • length – It is used to specify the number of characters to replace.
  • string – It is used to specify the string to insert.

Example:





Explanation:

In the above example, we are loading “books.xml” in the xmlDoc to get the text node of the first <title> element node. We are then replacing the eight first characters from the text node using the replaceData method.

Use of nodeValue Property:

Using the nodeValue property, we can easily replace the data in a text node.

Example:





Explanation:

In the above example, we will replace the text node value in the first <title> element. We will first load “books.xml” in the xmlDoc to get the text node of the first <title> element node. We will then change the text of the text node using the nodeValue property.