view raw
Puce Puce - 5 months ago 78
Java Question

XMLStreamWriter: indentation

is there really no way to directly write formatted XML using (Java SE 6)??? This is really unbelievable, as other XML APIs such as JAXB and some DOM libraries are able to do this. Even the .NET XMLStreamWriter equivalent is able to this AFAIK (if I remember correctly the class is System.Xml.XmlTextWriter).

This means the only option I have is to reparse the XML to generate formatted output??


StringWriter sw = new StringWriter();
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(sw);

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{}indent-amount", "4");

StringWriter formattedStringWriter = new StringWriter();
transformer.transform(new StreamSource(new StringReader(sw.toString())), new StreamResult(formattedStringWriter));

The problem with this solution is the property "{}indent-amount". I didn't find any documentation about it and it doesn't seem to be guaranteed to be portable.

So what other options do I have, if I want to do this with standard Java 6 classes? Create a JAXB or DOM object graph just for pretty printing??


You could add the necessary code to format your document in your writeXml method. Simply maintain a depth counter (to indicate the levels of nesting). Then before you writeStartElement and after you writeEndElement use the depth index to insert an indent.

for(int x=0; x<depth; x++) {
    xmlStreamWriter.writeCharacters("    ");