tags:

views:

243

answers:

2

Hi,

I am using StAX XML stream writer to write the XML file. It writes all the data in a single line. I want all the tags to be indented instead of a single line.

A: 

Answered here: http://stackoverflow.com/questions/290326/stax-xml-formatting-in-java

EDIT: A quick example (without resource cleaning) using stax-utils (https://stax-utils.dev.java.net/):

XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
FileOutputStream file = new FileOutputStream("d:/file.xml");
XMLEventWriter writer = xmlOutputFactory.createXMLEventWriter(file);
writer = new IndentingXMLEventWriter(writer);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
writer.add(eventFactory.createStartDocument());
writer.add(eventFactory.createStartElement("", "", "a"));
writer.add(eventFactory.createStartElement("", "", "b"));
writer.add(eventFactory.createEndElement("", "", "b"));
writer.add(eventFactory.createEndElement("", "", "a"));
writer.add(eventFactory.createEndDocument());

This gives you:

<?xml version="1.0" encoding="UTF-8"?>
<a>
  <b></b>
</a>
k_b
@k_b: I did check that, can you give some example having the code snippet to pass my xml file and set the indent option. In the example provided at the above location, I am not able to understand how to set all this params.
Anurag
I added an example to the post.
k_b
@k_b: Thanks, this is really helpful
Anurag
A: 

stax-utils (https://stax-utils.dev.java.net/) provides class IndentingXMLStreamWriter which does the job:

XMLStreamWriter writer =
  XMLOutputFactory.newInstance().createXMLStreamWriter(...);
writer = new IndentingXMLStreamWriter(writer);
...
chris
@chris - can you please name the jar file. I am not getting the download option at the given site.
Anurag
@Anurag - https://stax-utils.dev.java.net/files/documents/1519/50947/stax-utils-20070216.zip
chris