DOM Example For Creating a Child Node 


 

DOM Example For Creating a Child Node 

In this section, you will see how to create a child node in xml document.

In this section, you will see how to create a child node in xml document.

DOM Example For Creating a Child Node 

In this section we will discuss about how to add a Child Node in Dom document.

The addition of child node is a very logical. To add a child node first we create blank DOM document and then we create the root node using createElement() method . This root node is appended in the dom document using method appendChild().

After this step, we create child Node(element) for appending with the root node and we can set the attribute of the node by using method setAttribute("name","value") and append this child with the root node.

In this last step, we create the instance of TransformerFactory to create the object of the transformer class. This class is used to print the DOM tree (output) on the console.

The full code of the createchild.java:

import org.w3c.dom.*;
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

class createchild 
{
  public static void main(String[] args
  {
    try{
       DocumentBuilderFactory  factory = DocumentBuilderFactory.newInstance();
   
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
   
        Document doc = docBuilder.newDocument();
 
        Element root = doc.createElement("roseindia");   // create root
 
        doc.appendChild(root);   //append root 

            Element childElement = doc.createElement("spring");

           root.appendChild(childElement);

        TransformerFactory tranFactory = TransformerFactory.newInstance()
       Transformer aTransformer = tranFactory.newTransformer()
       Source src = new DOMSource(doc)
       Result dest = new StreamResult(System.out)
       aTransformer.transform(src, dest)//print the DOM tree on console

    }catch(Exception e){
      System.out.println(e.getMessage());
    }
  }
}

Output of the code:

c:\>java createchild
<?xml version="1.0"encoding="UTF-8"standalone="no"?>
   <roseindia>
                  <spring/>
    </roseindia>

Download The code

Ads