Creates a New DOM Parse Tree

In this section, describes a method to create a new DOM tree.

Creates a New DOM Parse Tree

Creates a New DOM Parse Tree

     

This Example describes a method to create a new DOM tree .Methods which are used for making a new DOM parse tree are described below :-

Element root = doc.createElement("places"):-it is a method to Create an Element node.

doc.appendChild(root):-This method adds a node after the last child node of the specified element root.

Element root = doc.getDocumentElement():-allows direct access to the root of the DOM document.

Xml code for the program generated is:-

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Document   : Document6.xml
    Created on : 10 July, 2008, 5:20 PM
    Author     : girish
    Description:
        Purpose of the document follows.
-->
<root>
</root>

Parsetree.java:-

/* 
 * @Program that Creates a New DOM Parse Tree
 * Parsetree.java 
 * Author:-RoseIndia Team
 * Date:-10-Jun-2008
 */

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Parsetree {

  public static void main(String[] args) throws Exception {
  DocumentBuilderFactory builderFactory = 
  DocumentBuilderFactory.newInstance();

  builderFactory.setValidating(false);
  builderFactory.setNamespaceAware(true);
  builderFactory.setIgnoringElementContentWhitespace(true);
  Document doc = builderFactory.newDocumentBuilder().parse(
   new 
File("Document6.xml"));
  new Parsetree().buildTree(doc);
  }

  public void buildTree(Document doc) {
  Element Companyname;
  Text text;
  Element root = doc.createElement("Company");
  doc.appendChild(root);
  Companyname = doc.createElement("Level");
  text = doc.createTextNode("SoftwareDevelopment");
  Companyname.appendChild(text);
  root.appendChild(Companyname);
  Companyname = doc.createElement("Location");
  text = doc.createTextNode("Rohini");
  Companyname.appendChild(text);
  root.appendChild(Companyname);
  Element root1=doc.getDocumentElement();
  System.out.print("Name of the root created is:- "+
  root.getNodeName());

  
  }
}

Output of the program:-

Name of the root created is:- Company

DownLoad Source Code