Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
XML
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Creating XML Tree

                         

This Example shows you how to Create an XMLTree in a DOM document. JAXP (Java API for XML Processing) is an interface which provides parsing of xml documents. Here the Document BuilderFactory is used to create new DOM parsers. Here we use "javax.xml.transform" package that defines the generic APIs to process transformation instructions, also performs a transformation from source to result. There are some of the methods used in code given below for Creating an XML Tree:-

Element root = doc.createElement("Company"):- This method creates an Element Node. Here "Company" is the String that specifies the name of the element node.

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

Text text = doc.createTextNode("Roseindia .Net"):- This method creates a Text Node. Here "Roseindia.Net" is the String that specifies the text for the  node.

Comment comment = doc.createComment("Employee in roseindia"):- This method creates a Comment Node. Here "Employee in roseindia" is the String that specifies the comment for the node.

TransformerFactory factory = TransformerFactory.newInstance():-TransformerFactory is a class that is used to create Transformer objects. A TransformerFactory  instance can be used to create Transformer and Templates objects.

transformer.transform(source, result):-This function organize data according to a style sheet as we are retrieving it from the File.

File file = new File("newxml.xml"):-Creates a new File.

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))):-BufferedWriter is used to write Text to the File.


Xmltree.java

/* 
 * @Program to create a DOM XML tree and then print the XML.
 * Xmltree.java 
 * Author:-RoseIndia Team
 * Date:-10-Jun-2008
 */

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

public class Xmltree {

    public static void main(String[] argsthrows Exception {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
        //creating a new instance of a DOM to build a DOM tree.
        Document doc = docBuilder.newDocument();
        new Xmltree().createXmlTree(doc);
    }

    public void createXmlTree(Document docthrows Exception {
        //This method creates an element node
        Element root = doc.createElement("Company");
        //adding a node after the last child node of the specified node.
        doc.appendChild(root);

        Element child = doc.createElement("Location");
        root.appendChild(child);

        Element child1 = doc.createElement("Companyname");
        child.appendChild(child1);

        Text text = doc.createTextNode("Roseindia .Net");
        child1.appendChild(text);

        Comment comment = doc.createComment("Employee in roseindia");
        child.appendChild(comment);

        Element element = doc.createElement("Employee");
        child.appendChild(element);

        Text text1 = doc.createTextNode("Girish Tewari");
        element.appendChild(text1);

        Element chilE = doc.createElement("Id");
            chilE.setAttribute("name""Girish");
            root.appendChild(chilE);

            // adding a text element to the child
            Text text12 = doc.createTextNode("status");
            chilE.appendChild(text12);
       
     //TransformerFactory instance is used to create Transformer objects. 
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
       
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File("newxml.xml");
        BufferedWriter bw = new BufferedWriter
                      (
new OutputStreamWriter(new FileOutputStream(file)));
        bw.write(xmlString);
        bw.flush();
        bw.close();
        // print xml
        System.out.println("Xml file created is :\n" + xmlString);
    }
}


Output of the program

Xml file created is :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Company>
<Location>
<Companyname>Roseindia .Net</Companyname>
<!--Employee in roseindia-->
<Employee>Girish Tewari</Employee>
</Location>
<Id name="Girish">status</Id>
</Company>



DownLoad SourceCode

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Latest Searches:
valueChangeListener
populate html dropdown
test
Introduction to jquery
tables pdf itext
File Validation code
populate html form da
href
clear the screen in ja
increase size of butto
pass arraylist in java
PHP Hits or visits cou
jdk1.6.0_07
java merge two xml doc
how to assign a value
java button event fram
create simole aaplicat
how to get IP address
DOM
Tree view in JSP
how to do Data Migrati
flex
jsp table
standered
round
PreparedStatement Upda
volume control midlet
getwindowwidthandheigh
login session servlet
Socket tcp
j2me Collection
setting of classpath i
read space character f
covert uppercase to lo
struts jar files
return an object in me
server means
Berry
digital clock in java
jdbc connections
web service with hiber
javascript drag drop w
create du table
jfreechart
Javascript Menus Image
Take user input using
core java Applets
hibernate2 Tomcat5.5 s
ajax with jsp chat
hibernate basics
Servlet Example To Dis
Button
Fetching Data From Dat
Ajax with JSP
covertir string to bin
create tree in swt usi
JSF tree collapse
example of JFileChoos
javapdfs
Internationalization u
covertir texte to bina
Sample program fetch d
connection sql throug
how to traverse throug
Action elements in jsp
diff b/w function and
page refresh
Flex Java Tutorial
h:inputtext tag in jsf
read and compare conte
ospf
polemophsm
mail merge in word
pthread.h in c
Convert Integer to Flo
struts application fro
JSP scriptlets
how to retrieve databa
jsf selectitems
jsp laglib
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.