Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting XML file using StAX

Tags:

java

xml

stax

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.

like image 617
Anurag Avatar asked Dec 10 '22 15:12

Anurag


2 Answers

stax-utils provides class IndentingXMLStreamWriter which does the job:

XMLStreamWriter writer =
  XMLOutputFactory.newInstance().createXMLStreamWriter(...);
writer = new IndentingXMLStreamWriter(writer);
...
like image 57
chris Avatar answered Dec 13 '22 22:12

chris


Answered here: 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>
like image 36
k_b Avatar answered Dec 13 '22 22:12

k_b