Using Dom4J: Writing An XML

In a previous post, see Using Dom4J: Reading An XML, I went over how to read in an XML document using Dom4J. Here I’ll show how to write an XML document using Dom4J. The first part to writing out an XML document is to have an in memory representation of it. Here is how you construct and XML document.

Document doc = DocumentFactory.getInstance()
Element root = doc.addElement("myroot");
root.addAttribute("myattr", "myval");
Element elem = root.addElement("myelem");
elem.addText("my text");

In this code you see how to create elements with child elements, how to add attributes and text data to elements. Once we have an in memory representation of the XML file, we can serialize it to the file system like this:

FileOutputStream fos = new FileOutputStream("simple.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(fos, format);

All this code will produce the following XML document:

<?xml version="1.0" encoding="UTF-8"?>

<myroot myattr="myval">
<myelem>my text</myelem>

2 Responses to “Using Dom4J: Writing An XML”

  • Karthic Raghavendra Says:

    Thanks for your tutorials. They help a lot.

    I tried running the above program and I get the following run time error. The program compiles fine though. I use Eclipse 3.2

    java.lang.NoSuchMethodError: com.trend.iwss.jscan.appscan.runtime.PolicyProps: method ()V not found
    at com.trend.iwss.jscan.appscan.runtime.Session.(
    at com.trend.iwss.jscan.appscan.runtime.Session.(
    at org.dom4j.DocumentFactory.(
    at org.dom4j.DocumentHelper.createDocument(
    at mypackage.XMLCreator.createDocument(
    at mypackage.XMLCreator.main(
    Exception in thread “main”

    Any help on solving it would be great.


    Karthic Raghavendra

  • Saji Says:

    The document is really useful , who are new to xml ..

Leave a Reply