Searching...
Wednesday, 19 September 2012

Java XML DOM4J Creating XML file Example

04:41
What is DOMJ4?
Dom4j is simple and easy to use open source library for Java XML,XPath and XSLT. This api will support DOM, SAX and JAXP.It is highly flexible and more memory efficient implementations of this framework.

Features of DOM4J

  • High flexible and memory efficient 
  • Support for Java collection framework while working with xml 
  • Support for JAXP,SAX,DOM,XSLT. 
  • It can work with large xml documents. 
  • Support XPath ,XSLT

DOM4J Creating XML file Example

Add below dependency in your pom.xml

<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
Or Download dom4j Jar from below repository
http://dom4j.sourceforge.net/

Important classes used

org.dom4j.Document->Specify xml documents
org.dom4j.DocumentHelper->Creates Document
org.dom4j.Element->Specify Element
org.dom4j.io.XMLWriter->Writes XML

Java class to create XML

package mycollectiontest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.*;

public class XMLExample {

public static void main(String[] args) {

// Creating document
Document document = DocumentHelper.createDocument();
Element order = document.addElement("Order");

// Creating element and setting attribute
Element orderNumber = order.addElement("OrderNumber");
orderNumber.addAttribute("Number", "1000");

// Creating other elements
Element orderItem = orderNumber.addElement("OrderItem");
orderItem.setText("Pen Drive");
Element orderItemDesc = orderNumber.addElement("OrderItemDescription");
orderItemDesc.setText("Trancsend 8 gb Pen Drive");

Element orderItemPrice = orderNumber.addElement("OrderItemPrice");
orderItemPrice.setText("500");
Element orderItemTax = orderNumber.addElement("OrderItemTax");
orderItemTax.setText("50");
Element orderItemTotal = orderNumber.addElement("OrderItemTotal");
orderItemTotal.setText("450");
// Writing document contents to xml file
XMLWriter output = null;
try {
output = new XMLWriter(new FileWriter(new File("order.xml")));
output.write(document);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Completed");

}

}
Output
<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber Number="1000">
<OrderItem>Pen Drive</OrderItem>
<OrderItemDescription>Trancsend 8 gb Pen Drive</OrderItemDescription>
<OrderItemPrice>500</OrderItemPrice>
<OrderItemTax>50</OrderItemTax>
<OrderItemTotal>450</OrderItemTotal>
</OrderNumber>
</Order>
Reference
http://dom4j.sourceforge.net/

0 comments: