Reading XML is half the story. Sooner or later you need to produce it: an export, a configuration file, a sitemap or a message for another system. dom4j makes building XML pleasant thanks to its chainable API. New here? Read our introduction to dom4j first.
Building a document from scratch
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
Document doc = DocumentHelper.createDocument();
Element library = doc.addElement("library").addAttribute("city", "Antwerp");
library.addElement("book")
.addAttribute("id", "b3")
.addAttribute("lang", "en")
.addElement("title").addText("Static sites in 2026");
Element book = library.element("book");
book.addElement("author").addText("Tom");
book.addElement("price").addAttribute("currency", "EUR").addText("14.99");Because addElement() returns the new child and addAttribute() and addText() return the element they were called on, you can build small structures in one readable chain.
Comments, CDATA and namespaces
library.addComment("Generated by our export job");
book.addElement("summary").addCDATA("<p>HTML is kept as-is in CDATA</p>");
// An element in a namespace, e.g. for a sitemap
Element urlset = DocumentHelper.createElement(
DocumentHelper.createQName("urlset",
DocumentHelper.createNamespace("", "http://www.sitemaps.org/schemas/sitemap/0.9")));Writing pretty-printed XML to a file
XMLWriter writes a document, element or any node. Combine it with OutputFormat to control indentation and encoding:
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
OutputFormat format = OutputFormat.createPrettyPrint(); // indent with two spaces
format.setEncoding("UTF-8");
try (OutputStream out = new FileOutputStream("library.xml")) {
XMLWriter writer = new XMLWriter(out, format);
writer.write(doc);
writer.flush();
}Use OutputFormat.createCompactFormat() for output without indentation – ideal for network messages where every byte counts.
Changing an existing document
Load a document as shown in our parsing guide, change it and write it back:
Element root = document.getRootElement();
// Change a value
Node price = document.selectSingleNode("//book[@id='b1']/price");
price.setText("17.50");
// Add an attribute to every book
for (Element b : root.elements("book")) {
b.addAttribute("status", "available");
}
// Remove a book
Element old = (Element) document.selectSingleNode("//book[@id='b2']");
if (old != null) {
old.detach();
}Getting XML as a String
String compact = doc.asXML();
StringWriter sw = new StringWriter();
XMLWriter writer = new XMLWriter(sw, OutputFormat.createPrettyPrint());
writer.write(doc);
writer.flush();
String pretty = sw.toString();Producing XML for the web? Our article on the importance of a sitemap explains why search engines love a clean XML sitemap – a perfect first project for dom4j.
Frequently asked questions
How do I get the XML as a String?
Call document.asXML() for compact output, or write to a StringWriter with an XMLWriter and OutputFormat.createPrettyPrint() for indented output.
Does dom4j escape special characters for me?
Yes. Text and attribute values you add are escaped when the document is written, so a & in your text becomes & in the output.