Here are some ways to emit well-formed XML using the Java 6 API.
Use LSSerializer:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element foo = doc.createElement("foo");
doc.appendChild(foo);
DOMImplementationLS lsImpl = (DOMImplementationLS) doc
.getImplementation();
LSOutput lsOut = lsImpl.createLSOutput();
lsOut.setByteStream(System.out);
LSSerializer lsSerializer = lsImpl.createLSSerializer();
lsSerializer.write(doc, lsOut);
This assumes your DOM parser implementation implements DOMImplementationLS.
Use a Transformer:
TransformerFactory tFactory = TransformerFactory
.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.transform(new DOMSource(doc),
new StreamResult(System.out));
Since the transformation API accepts a wide range of input and result types, this is probably the most flexible approach.
Another approach is to use the StAX API (see XMLStreamWriter and XMLEventWriter):
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter streamWriter = xmlOutputFactory
.createXMLStreamWriter(System.out);
streamWriter.writeStartDocument();
streamWriter.writeStartElement("foo");
streamWriter.writeEndElement();
streamWriter.writeEndDocument();
streamWriter.flush();
Using JAXB to marshal objects:
@XmlRootElement
class Foo {
}
JAXB.marshal(new Foo(), System.out);
I'm sure there are plenty of other ways to do this both in the Java 6 and in the numerous 3rd party Java XML APIs.