Share on Google+Share on Google+

DOM Example For Creating a Child Node 

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

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

class createchild 
  public static void main(String[] args
       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");


        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){

Output of the code:

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

Download The code


Posted on: September 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.