Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX
Produce correct XML from Java: build DOM trees with createElement(NS), setAttribute(NS) and text, CDATA and comment nodes, serialize them with the identity Transformer and output properties or LSSerializer, and stream XML directly with XMLStreamWriter, including namespaces and escaping.
kvi5hnuCode Sprout team member8 min readOn this page
The previous articles were about reading XML. Now we produce it. The obvious approach, printing tags with println and string concatenation, is a trap. Sooner or later a value contains &, < or a quote, and the output is no longer XML. The demo's last line shows exactly that. Let a library do the escaping. You have two good options:
- Build a DOM tree, then serialize it. This is convenient when you construct or modify a document in several steps, or already have a tree.
- Stream it with StAX (
XMLStreamWriter). This is efficient for large outputs, since no tree is kept in memory.
Building a DOM tree
Start with an empty document from a DocumentBuilder:
DocumentBuilder builder = DocumentBuilderFactory.newNSInstance().newDocumentBuilder();
Document doc = builder.newDocument();
The Document is a factory for all nodes:
Element root = doc.createElement("config");
Element child = doc.createElement("entry");
Text text = doc.createTextNode("Helvetica");
doc.appendChild(root);
root.appendChild(child);
child.appendChild(text);
child.setAttribute("id", "title");
setTextContent(s) replaces all children of an element with a single text node, which saves a step. createComment, createCDATASection and createProcessingInstruction create the other node types. insertBefore, replaceChild and removeChild rearrange nodes. A node belongs to the document that created it. To move a node into another document, call importNode (copy) or adoptNode (move) on the target document first.
Elements and attributes in namespaces
For namespaced documents, use the NS variants with a namespace URI and a qualified name:
String SVG = "http://www.w3.org/2000/svg";
Element svg = doc.createElementNS(SVG, "svg"); // default namespace
Element rect = doc.createElementNS(SVG, "svg:rect"); // with a prefix
link.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "https://example.com");
You don't have to create xmlns attributes yourself. The serializer adds the declarations that are needed when it writes the tree. Ordinary attributes such as width stay in no namespace, so plain setAttribute is right for them (article 44).
Writing a tree with a Transformer
Oddly, the DOM API itself (Level 2) has no method for writing a tree. The most common approach borrows the XSLT machinery (article 47): a Transformer without a stylesheet performs the identity transformation, copying its source to its result. With a DOMSource and a StreamResult, that means writing the tree as text:
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(doc), new StreamResult(Files.newOutputStream(path)));
StreamResult accepts a File, an OutputStream, a Writer or a system id. DOMSource can wrap any node, not only a whole document. Output properties control the format:
OutputKeys constant | Values | Effect |
|---|---|---|
METHOD | xml, html, text | output syntax |
INDENT | yes, no | line breaks and indentation |
ENCODING | UTF-8, ... | character encoding, also written into the declaration |
OMIT_XML_DECLARATION | yes, no | drop the <?xml ...?> line |
STANDALONE | yes, no | the standalone pseudo-attribute |
DOCTYPE_PUBLIC, DOCTYPE_SYSTEM | identifiers | write a <!DOCTYPE ...> declaration |
CDATA_SECTION_ELEMENTS | element names | write the text of these elements as CDATA |
The indentation amount isn't standardized. The JDK reads it from the implementation-specific property shown above (the default is 4 since JDK 9). The JDK's serializer has a few quirks. It writes standalone="no" for a DOM source unless you call doc.setXmlStandalone(true), and then it omits the line break after the declaration. It also doesn't put a comment before the root element on a separate line. If exact formatting matters, check the output or post-process it.
Writing a tree with LSSerializer
DOM Level 3 "Load and Save" added a proper serializer. It's reached through a feature lookup:
var implLS = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
LSSerializer serializer = implLS.createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", true);
String xml = serializer.writeToString(doc);
writeToString always produces a declaration claiming UTF-16, because a Java String is UTF-16. Turn it off with the parameter xml-declaration set to false if you embed the string elsewhere. To write a file in a particular encoding, use an LSOutput:
LSOutput output = implLS.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(outputStream);
serializer.write(doc, output);
Streaming with StAX
If the tree has no other purpose, building it just to write it out wastes memory. An XMLStreamWriter writes directly:
XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(out, "UTF-8");
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("config");
w.writeAttribute("version", "2");
w.writeStartElement("entry");
w.writeCharacters("Tom & Jerry"); // escaped as Tom & Jerry
w.writeEndElement();
w.writeEmptyElement("separator"); // <separator/>
w.writeEndDocument(); // closes all open elements
w.close();
writeCharacters and writeAttribute escape <, & and quotes as necessary. Other methods write comments, CDATA sections, processing instructions and DTDs. A few points to be aware of:
- Namespaces are your job.
writeStartElement(uri, localName)uses a prefix that you've bound withsetPrefixorsetDefaultNamespace, but those calls don't write the declaration. CallwriteNamespace(prefix, uri)orwriteDefaultNamespace(uri)right after the start element. Alternatively, set the factory propertyXMLOutputFactory.IS_REPAIRING_NAMESPACESto true, and the writer adds declarations automatically. - There's no well-formedness checking. The writer happily produces two root elements or
--inside a comment, as the demo shows. - There's no indentation. You can write line breaks and spaces with
writeCharacters, or pipe the output through an indentingTransformer. - Close it explicitly.
XMLStreamWriterisn'tAutoCloseable, so usetry/finally. Itsclosemethod doesn't close the underlying stream either.
XMLEventWriter is the event-object counterpart. It accepts XMLEvents from an XMLEventFactory or straight from an XMLEventReader, which makes it easy to copy a document while changing a few events.
The program
The demo draws a little "modern art" picture: four colored rectangles chosen with a seeded random generator, saved as SVG. It builds the picture as a DOM tree, including a title with characters that must be escaped, a namespaced xlink:href attribute and a CDATA section. It writes the tree with an indenting Transformer, then writes one element with a DOCTYPE. It writes the tree with LSSerializer to a temporary file and parses the file back. Next it produces equivalent output with XMLStreamWriter, shows that the stream writer doesn't check well-formedness, and finally shows what string concatenation produces.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.stream.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.w3c.dom.ls.*;
public class Solution {
static final String SVG = "http://www.w3.org/2000/svg";
static final String XLINK = "http://www.w3.org/1999/xlink";
record Rect(int x, int y, int w, int h, String color) { }
static List<Rect> painting(long seed) {
var random = new Random(seed);
String[] palette = {"#e63946", "#f1c453", "#1d3557", "#2a9d8f"};
var rects = new ArrayList<Rect>();
for (int i = 0; i < 4; i++)
rects.add(new Rect(random.nextInt(200), random.nextInt(100), 20 + random.nextInt(80),
20 + random.nextInt(60), palette[random.nextInt(palette.length)]));
return rects;
}
/** Build an SVG document as a DOM tree. */
static Document buildDom(List<Rect> rects) throws ParserConfigurationException {
Document doc = DocumentBuilderFactory.newNSInstance().newDocumentBuilder().newDocument();
Element svg = doc.createElementNS(SVG, "svg");
svg.setAttribute("width", "300");
svg.setAttribute("height", "200");
doc.appendChild(svg);
doc.insertBefore(doc.createComment(" generated <art> & more "), svg);
Element title = doc.createElementNS(SVG, "title");
title.setTextContent("Rects \"A\" & <B>"); // escaped automatically
svg.appendChild(title);
for (Rect r : rects) {
Element rect = doc.createElementNS(SVG, "rect");
rect.setAttribute("x", "" + r.x());
rect.setAttribute("y", "" + r.y());
rect.setAttribute("width", "" + r.w());
rect.setAttribute("height", "" + r.h());
rect.setAttribute("fill", r.color());
svg.appendChild(rect);
}
Element link = doc.createElementNS(SVG, "a");
link.setAttributeNS(XLINK, "xlink:href", "https://example.com/?a=1&b=2");
link.appendChild(doc.createCDATASection("if (x < y)"));
svg.appendChild(link);
return doc;
}
public static void main(String[] args) throws Exception {
List<Rect> rects = painting(42);
Document doc = buildDom(rects);
System.out.println("--- Transformer: identity transformation ---");
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
doc.setXmlStandalone(true); // otherwise standalone="no" is written
var text = new StringWriter();
t.transform(new DOMSource(doc), new StreamResult(text));
System.out.println(text.toString().strip());
System.out.println("--- Transformer: DOCTYPE and no declaration ---");
Transformer t2 = TransformerFactory.newInstance().newTransformer();
t2.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.1//EN");
t2.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd");
t2.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
var withDoctype = new StringWriter();
t2.transform(new DOMSource(doc.getElementsByTagNameNS(SVG, "rect").item(0)), new StreamResult(withDoctype));
System.out.println(withDoctype);
System.out.println("--- LSSerializer ---");
var implLS = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
LSSerializer serializer = implLS.createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", true);
serializer.getDomConfig().setParameter("xml-declaration", false);
String s = serializer.writeToString(doc.getElementsByTagNameNS(SVG, "title").item(0));
System.out.println("writeToString(title): " + s.strip());
Path file = Files.createTempFile("art", ".svg");
try {
LSOutput output = implLS.createLSOutput();
output.setEncoding("UTF-8");
try (var out = Files.newOutputStream(file)) {
output.setByteStream(out);
serializer.write(doc, output);
}
Document back = DocumentBuilderFactory.newNSInstance().newDocumentBuilder().parse(file.toFile());
System.out.println("written and re-read: " + back.getElementsByTagNameNS(SVG, "rect").getLength()
+ " rects, title \"" + back.getElementsByTagNameNS(SVG, "title").item(0).getTextContent() + "\"");
} finally {
Files.delete(file);
}
System.out.println("--- StAX XMLStreamWriter ---");
var bytes = new ByteArrayOutputStream();
XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(bytes, "UTF-8");
try {
w.writeStartDocument("UTF-8", "1.0");
w.setDefaultNamespace(SVG);
w.writeStartElement(SVG, "svg");
w.writeDefaultNamespace(SVG);
w.writeNamespace("xlink", XLINK);
w.writeAttribute("width", "300");
w.writeAttribute("height", "200");
w.writeStartElement(SVG, "title");
w.writeCharacters("Rects \"A\" & <B>");
w.writeEndElement();
for (Rect r : rects) {
w.writeEmptyElement(SVG, "rect");
w.writeAttribute("x", "" + r.x());
w.writeAttribute("y", "" + r.y());
w.writeAttribute("fill", r.color());
}
w.writeStartElement(SVG, "a");
w.writeAttribute(XLINK, "href", "https://example.com/?a=1&b=2");
w.writeCData("if (x < y)");
w.writeEndDocument(); // closes open elements
} finally {
w.close(); // not AutoCloseable; does not close the stream
}
String stax = bytes.toString(StandardCharsets.UTF_8);
System.out.println(stax);
System.out.println("--- StAX does not check well-formedness ---");
var sw = new StringWriter();
XMLStreamWriter loose = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
loose.writeStartElement("a");
loose.writeEndElement();
loose.writeStartElement("b"); // a second root element
loose.writeComment(" -- "); // not allowed in a comment
loose.writeEndDocument();
loose.close();
System.out.println(sw);
System.out.println("--- never by string concatenation ---");
String name = "Tom & \"Jerry\" <cat>";
String naive = "<pet name=\"" + name + "\"/>";
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler() {
@Override public void fatalError(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXParseException { throw e; }
});
builder.parse(new org.xml.sax.InputSource(new StringReader(naive)));
} catch (org.xml.sax.SAXParseException e) {
System.out.println("naive output is not XML: " + e.getMessage());
}
}
}
--- Transformer: identity transformation ---
<?xml version="1.0" encoding="UTF-8"?><!-- generated <art> & more --><svg height="200" width="300" xmlns="http://www.w3.org/2000/svg">
<title>Rects "A" & <B></title>
<rect fill="#f1c453" height="64" width="68" x="130" y="63"/>
<rect fill="#e63946" height="39" width="58" x="125" y="5"/>
<rect fill="#f1c453" height="32" width="96" x="182" y="2"/>
<rect fill="#2a9d8f" height="63" width="30" x="32" y="56"/>
<a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://example.com/?a=1&b=2"><![CDATA[if (x < y)]]></a>
</svg>
--- Transformer: DOCTYPE and no declaration ---
<!DOCTYPE rect PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<rect fill="#f1c453" height="64" width="68" x="130" y="63" xmlns="http://www.w3.org/2000/svg"/>
--- LSSerializer ---
writeToString(title): <title xmlns="http://www.w3.org/2000/svg">Rects "A" & <B></title>
written and re-read: 4 rects, title "Rects "A" & <B>"
--- StAX XMLStreamWriter ---
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="200"><title>Rects "A" & <B></title><rect x="130" y="63" fill="#f1c453"/><rect x="125" y="5" fill="#e63946"/><rect x="182" y="2" fill="#f1c453"/><rect x="32" y="56" fill="#2a9d8f"/><a xlink:href="https://example.com/?a=1&b=2"><![CDATA[if (x < y)]]></a></svg>
--- StAX does not check well-formedness ---
<a></a><b><!-- -- --></b>
--- never by string concatenation ---
naive output is not XML: The entity name must immediately follow the '&' in the entity reference.
Open the generated SVG in any browser to see the picture. All three writers escaped the title and the & in the URL correctly. The comment kept its < and & unescaped, which is legal inside comments.
Common questions
How do I pretty-print an existing XML string?
Parse it, then write it with an indenting identity Transformer. Whitespace-only text nodes from the original can produce odd blank lines. Remove them first, for example with XPath //text()[normalize-space()=''], then delete each node.
Why is there an empty line between elements after indenting? The same cause: the tree already contains whitespace text nodes, and the serializer adds its own line breaks. Strip whitespace-only text nodes before writing, or parse with a validating parser that ignores element-content whitespace.
How do I write a file in UTF-8 regardless of the platform?
Transformer, LSSerializer and XMLStreamWriter default to UTF-8 when writing bytes. Pass an OutputStream or Path-based target (not a Writer of unknown encoding), and if you use a Writer, make it UTF-8 and declare the same encoding (OutputKeys.ENCODING, or writeStartDocument("UTF-8", "1.0")).
How do I write characters that aren't allowed in XML 1.0, such as \u0000?
You can't. Most control characters below U+0020 (except tab, newline and carriage return) are illegal in XML 1.0, even as character references. DOM happily stores them, but the JDK's Transformer then fails with "An invalid XML character (Unicode: 0x1) was found". Encode such data, for example in Base64, before putting it into a document.
Does XMLStreamWriter check that my output is well-formed?
Not fully. It escapes text but doesn't verify that elements are balanced or that names are legal. Close elements carefully, call writeEndDocument() to close open ones, and parse the result in a test.
Can I keep the original formatting when I modify a document? Not with DOM, StAX or XSLT in the JDK: all of them lose attribute quote style, whitespace inside tags and attribute order. For minimal-change edits on hand-maintained files, use a tool built for round-tripping, or edit the text directly at positions found by a parser.
API reference
| API | Purpose |
|---|---|
DocumentBuilder.newDocument() | empty document |
Document.createElement(name), createElementNS(uri, qname) | new element |
Document.createTextNode, createComment, createCDATASection, createProcessingInstruction | other nodes |
Node.appendChild, insertBefore, replaceChild, removeChild | build and rearrange the tree |
Element.setAttribute(name, value), setAttributeNS(uri, qname, value) | attributes |
Node.setTextContent(text) | replace the children with text |
Document.importNode(node, deep), adoptNode(node) | bring nodes in from another document |
TransformerFactory.newInstance().newTransformer() | identity transformer |
Transformer.setOutputProperty(OutputKeys.X, value) | output format |
Transformer.transform(new DOMSource(node), new StreamResult(target)) | write a tree |
DOMImplementationLS.createLSSerializer(), LSSerializer.writeToString, write | DOM Level 3 serializer |
XMLOutputFactory.newInstance().createXMLStreamWriter(out, encoding) | streaming writer |
XMLStreamWriter.writeStartElement, writeAttribute, writeCharacters, writeEndElement | write content |
writeNamespace, writeDefaultNamespace, setPrefix, setDefaultNamespace | namespace handling |
XMLOutputFactory.IS_REPAIRING_NAMESPACES | automatic namespace declarations |
Summary
- Never assemble XML with string concatenation. Use an API that escapes for you.
- Build trees with the
Document'screate...methods andappendChild. Use theNSmethods for namespaces, and the serializer writes the declarations. - Write a tree with the identity
Transformerand output properties such asINDENT,DOCTYPE_SYSTEMandOMIT_XML_DECLARATION, or withLSSerializer. - For large outputs, stream with
XMLStreamWriter. Declare namespaces yourself (or enable namespace repairing), and close the writer explicitly. It doesn't check well-formedness or indent.
Practice Questions
What's wrong with out.println("\<name\>" + name + "\</name\>"), and what would you use instead?
If name contains < or &, the output isn't well-formed. If it contains a crafted string such as </name><admin>true</admin><name>, it can even inject elements. Use XMLStreamWriter.writeCharacters(name) or a DOM text node with a serializer, which escape the text.
How do you write a DOM tree to a file with indentation and a DOCTYPE?
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "config.dtd");
t.transform(new DOMSource(doc), new StreamResult(path.toFile()));
An XMLStreamWriter produces \<s:order\> without any xmlns:s declaration, and the output can't be parsed with namespace awareness. What was missed?
setPrefix("s", uri) only binds the prefix inside the writer. It doesn't write the declaration. After writeStartElement(uri, "order"), call writeNamespace("s", uri), or create the writer from a factory with IS_REPAIRING_NAMESPACES set to true.
Why does LSSerializer.writeToString produce encoding="UTF-16" in the declaration?
It returns a Java String, whose characters are UTF-16, so the declaration describes that encoding. If you write the string to a UTF-8 file, the declaration is wrong. Either turn off the declaration with the xml-declaration parameter, or write directly to a byte stream with an LSOutput whose encoding is set.
When should you prefer XMLStreamWriter over building a DOM tree?
When the output is large or generated in one pass from other data, such as exporting database rows, because a stream writer needs almost no memory. A DOM tree is preferable when the document is built or modified in several steps, needs reordering, or must be validated or queried before it's written.
Previous: Streaming XML Parsers in Java: SAX and StAX
Next: XSL Transformations in Java: Stylesheets and the Transformer API
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.