XML DOM Change Node Values

To change a node value, the nodeValue property is used, while, to change the value of an attribute, the setAttribute() method is used.

Change the Value of an Element:

Everything in the DOM is a node. There is no text value in the element nodes. It is stored in a child node, also called a text node. The value of the elements’ text node is required to be changed to change the text value of the element.

Change the Value of a Text Node:

To change the value of a text node, the nodeValue property is used.

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

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


Example:





Explanation:

In the above example, we are loading “books.xml” in the xmlDoc to change the text node value of the first <title> element.

Example: To loop through and change the text node of all <title> elements:





Explanation:

In the above example, we are loading “books.xml” in the xmlDoc to change the text node value of all the <title> elements.

Change the Value of an Attribute:

Attributes in a DOM are nodes. The attribute nodes, however, have text values, unlike the element nodes. Thus, to change the text value of an attribute node, we have to change its value using either of the two methods:

  • Using the setAttribute() method
  • Setting the nodeValue property of the attribute node.

Change an Attribute Using the setAttribute() method:

To change the value of an attribute, we can use the setAttribute() method, which creates a new attribute, in case the attribute does not exist.

Example:





Output:

Explanation:

In the above example, we are changing the category attribute of the <book> element. Here, we are loading the “books.xml” in the xmlDoc to get the first <book> element. We are then changing the “category” attribute value. In case, the attribute does not exist a new attribute is created with the specified name and value.

Example: To loop through all <title> elements and to add a new attribute:





Explanation:

In the above example, we are loading the “books.xml” in the xmlDoc to get all the <title> elements. We are then adding a new attribute to each of them.

Change an Attribute Using nodeValue:

The value of an attribute node can be retrieved by using the nodeValue property. The value of the attribute changes if we change the value property.

Example:

 



Explanation:

In the above example, we are loading the “books.xml” in the xmlDoc to get the “category” attribute of the first <book> element. We are then changing the attribute node value.

Please follow and like us:
Content Protection by DMCA.com