Dom4j XML Creation

I was trying to create a XML file using Dom4j yesterday. For those, who don't know about it, here is a gentle introduction. Dom4j is a open source library to work with XML, XSLT and XPATH in Java platform. It just makes the working with XML files so easy.

The official website link is here. Grab the download before you start to work with the example here.

Here is a neat working example of creating an XML using Dom 4J and writing it to a file.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class foo {

Document document;

public void createdoc() {

document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );
Element author1 = root.addElement( "author" )
.addAttribute( "name", "123" )
.addAttribute( "location", "UK" )
.addText( "James" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "UK" )
.addText( "Bob" );


public void writedoc() {

try {

XMLWriter writer = new XMLWriter(new FileWriter( "out.xml" ));

catch (Exception f) {




public static void main(String args[]) {

foo xc = new foo();



This code when compiled and executed will create a neat XML and write the XML to the output file 'out.xml'. Keep watching this space for more examples on Dom4j.

No comments:

Post a Comment