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()
	.createDocument();
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);
writer.write(doc);
writer.flush();

All this code will produce the following XML document:

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

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

Related posts:

  1. Using Dom4J: Reading An XML File
  2. The Word Is POI
  3. Escape From XML
  4. XML Object Cereal
  5. CDATA With XSLT
  6. WordprocessingML


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.(Session.java:58)
    at com.trend.iwss.jscan.appscan.runtime.Session.(Session.java:33)
    at org.dom4j.DocumentFactory.(DocumentFactory.java)
    at org.dom4j.DocumentHelper.createDocument(DocumentHelper.java:34)
    at mypackage.XMLCreator.createDocument(XMLCreator.java:16)
    at mypackage.XMLCreator.main(XMLCreator.java:59)
    Exception in thread “main”

    Any help on solving it would be great.

    Regards

    Karthic Raghavendra

  • Saji Says:

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

Leave a Reply