XML DOM Add Nodes

We can add a child node to an existing node using the appendChild() method. The addition of the new node is done only after any existing child nodes. If we need to specify the position of the node, we can use the insertBefore() method.

Books.xml:




  
    ABC
    Author Name
    2020
    29.99
  

  
    Basics
    Author 1
    Author 2
 
 2005
    49.99
  


Example:





Output:

Explanation:

In the above example, we are creating the <publisher> element to add it after the last child of the first <book> element. Here, we will first load “books.xml” in the xmlDoc.

Example:





Output:

Explanation:

In the above example, we are creating the <publisher> element to add it after the last child of the first <book> element, but here the new element is added with a value. For this, we will first load “books.xml” in the xmlDoc before creating the node and a new text node “Publisher Name”. We will then append the text node to the <publisher> node and the <publisher> node to the <book> element.

Insert a Node – insertBefore() method:

To insert a node before a specified child node, the insertBefore() method is used, especially when the position of the added node is crucial.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. Here, we are creating a new element node <book> to be inserted in front of the last <book> element node. The new node will be added after the last existing child node, in case the second parameter of insertBefore() is null. To append a new child node to x, we are using x.insertBefore(newNode,null) and x.appendChild(newNode).

Add a New Attribute:

To set the value of an attribute, the setAttribute() method is used. In the absence of any method called add Attribute(), the setAttribute() takes the charge to create a new attribute if the attribute does not exist and to overwrite the existing value, if the attribute already exists.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then set the value of the attribute “publisher” to “Publisher Name” for the first <book> element.

Add Text to a Text Node – insertData() method:

To insert data into an existing text node, the insertData() method is used. It has two parameters:

  • offset – It is used to specify where to begin inserting characters. The offset value starts at zero.
  • string – It is used to specify the string to insert.

Example:





Output:

Explanation:

In the above example, we are adding text to the text node of the first <title> element of books.xml.