views:

2374

answers:

6

Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:

<element1>
  <element2>
   someData
  </element2>
</element1>

instead of:

<element1><element2>someData</element2></element1>

If this is not possible in woodstox, is there any other lightweight libs that can do this?

A: 

If you're using the iterating method (XMLEventReader), can't you just attach a new line '\n' character to the relevant XMLEvents when writing to your XML file?

Spencer K
+4  A: 

Not sure about another lib, or how the lib you are using works, but if its based on the jdk, but you can set the attribute:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

To accomplish this. Or take a look at the following for a stax approach

Josh
The link to the approach misses a colon after the https
Paul de Vrieze
+1  A: 

Not sure about stax, but there was a recent discussion about pretty printing xml here

pretty print xml from java

this was my attempt at a solution

http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java#260314

using the org.dom4j.io.OutputFormat.createPrettyPrint() method

mlo55
+2  A: 

How about StaxMate (http://staxmate.codehaus.org):

http://www.cowtowncoder.com/blog/archives/2006/09/entry_21.html

Works well with Woodstox, fast, low-memory usage (no in-memory tree built), and indents like so:


SMOutputFactory sf = SMOutputFactory(XMLOutputFactory.newInstance());
SMOutputDocument doc = sf.createOutputDocument(new FileOutputStream("output.xml"));
doc.setIndentation("\n ", 1, 2); // for unix linefeed, 2 spaces per level    
// write doc like:    
SMOutputElement root = doc.addElement("elem1");    
root.addElement("element2").addCharacters("someData");    
doc.closeRoot(); // important, flushes, closes output


StaxMan
+2  A: 

If you're using the StAX cursor API, you can indent the output by wrapping the XMLStreamWriter in an indenting proxy. I tried this in my own project and it worked nicely.

Andrew Swan
+1 glad to hear it worked for you :)
ewernli
A: 

There is com.sun.xml.txw2.output.IndentingXMLStreamWriter

XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
Juha Syrjälä