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.
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>
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Creating XML Tree
Post your Comment