Sunday, August 3, 2014

Program for creation of XML document using DOM4J

DOM4J is an open-source java library for programming XML in java. 

I used Eclipse as the IDE and Java SE 7 Update 25 for developing the program. 

One have to download the DOM4J jars to start with. It can be downloaded from here DOM4J archive Download link

Once downloaded Unrar the rar file and consolidate all the jars from the folders and browse them into the build path of the Eclipse that you're using. Click ALT+ENTER on the project and properties window will open up, navigate to the Java Build Path section, in the Libraries tab click the button Add external jars and browse all the consolidated jars.


 The Eclipse project can be a simple java project.

DOM4J Program:
You can use this program to create the xml document using DOM4J. 

 package com.dom4j.xml;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.io.StringReader;  
 import java.io.StringWriter;  
 import javax.xml.transform.OutputKeys;  
 import javax.xml.transform.Source;  
 import javax.xml.transform.Transformer;  
 import javax.xml.transform.TransformerConfigurationException;  
 import javax.xml.transform.TransformerException;  
 import javax.xml.transform.TransformerFactory;  
 import javax.xml.transform.stream.StreamResult;  
 import javax.xml.transform.stream.StreamSource;  
 import org.dom4j.Document;  
 import org.dom4j.DocumentHelper;  
 import org.dom4j.Element;  
 public class XMLCreation {  
      /**  
       * This method creates XML document upon calling.  
       */  
      private void createXML() {  
           Document document = DocumentHelper.createDocument();  
           Element root = document.addElement("Root");  
           Element child1 = root.addElement("Child1")  
                     .addAttribute("attr1", "attr1val")  
                     .addAttribute("loopNode", "no");  
           Element child2 = child1.addElement("Child2").addAttribute("loopNode",  
                     "no");  
           {  
                for (int i = 0; i < 3; i++) {  
                     Element loopNode = child2.addElement("Loop" + i);  
                     loopNode.addAttribute("loopNode", "yes");  
                     loopNode.addText("Loop Child " + i);  
                }  
           }  
           Source source = new StreamSource(new StringReader(document.asXML()));  
           StringWriter stringWriter = new StringWriter();  
           StreamResult streamResult = new StreamResult(stringWriter);  
           File file = null;  
           BufferedWriter bufferedWriter = null;  
           try {  
                file = new File("C:/DemoXMLFile1.xml");  
                file.createNewFile();  
                TransformerFactory transformerFactory = TransformerFactory  
                          .newInstance();  
                Transformer transformer = transformerFactory.newTransformer();  
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
                transformer.setOutputProperty(  
                          "{http://xml.apache.org/xslt}indent-amount", "9");  
                transformer.transform(source, streamResult);  
                bufferedWriter = new BufferedWriter(new FileWriter(  
                          file.getAbsoluteFile()));  
                bufferedWriter.write(streamResult.getWriter().toString());  
                bufferedWriter.flush();  
                bufferedWriter.close();  
           } catch (FileNotFoundException f) {  
                f.printStackTrace();  
           } catch (TransformerConfigurationException t) {  
                t.printStackTrace();  
           } catch (IOException i) {  
                i.printStackTrace();  
           } catch (TransformerException t) {  
                t.printStackTrace();  
           }  
      }  
      /**  
       * Main method  
       *   
       * @param args  
       */  
      public static void main(String args[]) {  
           new XMLCreation().createXML();  
      }  
 }  

1. The process is pretty straight forward. I used Document interface and created an instance to it. 
2. I used this instance to create a root element using Element interface. I added attributes to the node. 
3. Further I created another Element instance and added node as child to the above root element and attributes.
4. I created a loop and every time loop iterates it creates child node to the sub child node and adds text to the loop node. 
5. I made use of TransformerFactory and Transformer to format the xml document. 
6. The normal BufferedWriter to write the xml to the document. 
7. The interface Source stores the document xml details in StringReader, the StringReader creates characterstream. 
8. I created an object to StringWriter class and passed the instance to the StreamResult interface. 
9. The StringWriter converts character stream to the buffered stream. 
10. To the transformer we have included output properties to provide indent to the xml file using setOutputProperty.

One can also use the Scanner class to provide file paths and file names as dynamic parameters.

The output file I got with Indent 9:



Suggestions are welcome. Please feel free to comment.

Comments

blog comments powered by Disqus