XML DOM Create Nodes

To create a new element node, we can use the createElement() 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 loading “books.xml” in the xmlDoc. We will then create a new element node <publisher> to append it to the first <book> element.

Example: To loop through and to add an element to all <book> elements:





Output:

Create a New Attribute Node:

A new attribute node is created using the createAttribute() method. In case there is already an attribute existing with the same name then it will be replaced by the new one.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then create a new attribute node <publisher> and will set its value to “Publisher Name”. This new attribute node is added to the first <title> element.

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





Output:

Create an Attribute Using the setAttribute() method:

To create a new attribute, if it is not existing already, the setAttribute() method is used.

Example:





Output:

Explanation:

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

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





Output:

Create a Text Node:

We can create a new text node using the createTextNode() method.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then create a new element node <publisher> and a new text node with the text “first”. The final step is to append the new text node to the element node and the new element node to the first <book> element.

Example: To add an element node, with a text node, to all <book> elements:





Output:

Create a CDATA Section Node:

To create a new CDATA section node, the createCDATASection() method is used.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then create a new CDATA section node to append it to the first <book> element.

Example: To loop through, and to add a CDATA section, to all <book> elements:





Output:

Create a Comment Node:

We can use the createComment() method to create a new comment node.

Example:





Output:

Explanation:

In the above example, we are loading “books.xml” in the xmlDoc. We will then create a new comment node to append it to the first <book> element.

Example: To loop through, and to add a comment node, to all <book> elements:





Output: