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>