StAX XML formatting in Java

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?


Asked by: Kate184 | Posted: 28-01-2022






Answer 1

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

XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));

Answered by: Julia633 | Posted: 01-03-2022



Answer 2

Using the JDK Transformer:

public String transform(String xml) throws XMLStreamException, TransformerException
{
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Writer out = new StringWriter();
    t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
    return out.toString();
}

Answered by: Melissa727 | Posted: 01-03-2022



Answer 3

Via the JDK: transformer.setOutputProperty(OutputKeys.INDENT, "yes");.

Answered by: Cherry828 | Posted: 01-03-2022



Answer 4

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.

Answered by: Steven730 | Posted: 01-03-2022



Answer 5

Rather than relying on a com.sun...class that might go away (or get renamed com.oracle...class), I recommend downloading the StAX utility classes from java.net. This package contains a IndentingXMLStreamWriter class that works nicely. (Source and javadoc are included in the download.)

Answered by: Maya871 | Posted: 01-03-2022



Answer 6

How about StaxMate:

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 = new 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("element1");    
root.addElement("element2").addCharacters("someData");    
doc.closeRoot(); // important, flushes, closes output

Answered by: Kirsten869 | Posted: 01-03-2022



Answer 7

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?

Answered by: Michelle512 | Posted: 01-03-2022



Answer 8

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

How to pretty print XML from Java?

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

Answered by: Walter393 | Posted: 01-03-2022



Answer 9

if you are using XMLEventWriter, then an easier way to do that is:

XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter writer = outputFactory.createXMLEventWriter(w);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        Characters newLine = eventFactory.createCharacters("\n"); 
        writer.add(startRoot);
        writer.add(newLine);

Answered by: Wilson706 | Posted: 01-03-2022



Answer 10

With Spring Batch this requires a subclass since this JIRA BATCH-1867

public class IndentingStaxEventItemWriter<T> extends StaxEventItemWriter<T> {

  @Setter
  @Getter
  private boolean indenting = true;

  @Override
  protected XMLEventWriter createXmlEventWriter( XMLOutputFactory outputFactory, Writer writer) throws XMLStreamException {
    if ( isIndenting() ) {
      return new IndentingXMLEventWriter( super.createXmlEventWriter( outputFactory, writer ) );
    }
    else {
      return super.createXmlEventWriter( outputFactory, writer );
    }
  }

}

But this requires an additionnal dependency because Spring Batch does not include the code to indent the StAX output:

<dependency>
  <groupId>net.java.dev.stax-utils</groupId>
  <artifactId>stax-utils</artifactId>
  <version>20070216</version>
</dependency>

Answered by: Anna126 | Posted: 01-03-2022



Similar questions

formatting - Any command line format tool available for java file?

We are working on a legacy system (7 years old), with lots of java/jsp files that have never been formatted before, not reader at all. Because we have many old versions, we are afraid that we won't be able to effectively diff unformatted and formatted files anymore if we format them. Are there any command line format tools available with which we can format the old version of the file before doing ...


java - Jlabel HTML formatting

I have a JLabel which has an e-mail address in it. I used HTML formatting on the JLabel, so it appears as a link. However, you are not able to click the link. In fact, you cannot select any of the text in the label. Is there a property that I can set on the JLabel to allow the user to at least select the text of the e-mail, and preferably to click on the e-mail address the way they would on a webpage? My code for m...


Java date formatting?

I want to read a date in the format YYYY-MM-DD. But if I enter date say for example 2008-1-1, I want to read it as 2008-01-01. Can anybody help me? Thanks in advance


java - What's the best design pattern for formatting numbers?

I need to write the code that would format the value according to the specified options. Right now there is several formatting options that can be chosen: rounding/truncating the number with the specified precision, added prefix (e.g $) or postfix (e.g. %), grouping thousands (applying commas), adding numeric abbreviations (KMB). So e.g. number 1857 could be displayed as $2K or $1.86K or $ 1,867 At...


formatting - Java: Format number in millions

Is there a way to use DecimalFormat (or some other standard formatter) to format numbers like this: 1,000,000 =&gt; 1.00M 1,234,567 =&gt; 1.23M 1,234,567,890 =&gt; 1234.57M Basically dividing some number by 1 million, keeping 2 decimal places, and slapping an 'M' on the end. I've thought about creating a new subclass of NumberFormat but it looks trickier than ...


java - BIRT Formatting Legend of a bar chart

I have a small problem, a BIRT report I designed uses a bar chart. Now I want to increase the space between colored box and the text in the legend. Is that possible? (I'm using BIRT 2.1.3) http://www.fotos-hochladen.net/barchartproblemhng05e76.png EDIT: I forgot to mention I am using BIRT 2.1.3 with the RCP De...


java - Formatting orb tags in MVEL

How to remove the whitespace line generated by @code{}, @if{}, @foreach{}, @end{} etc or Tags in the result of MVEL 2.0 templating?


formatting - Java: Currency to Locale Mapping Possible?

I have a value stored in a DB correlating to a monetary amount, say 10.0. I also have access to the Currency/CurrencyCode. How can I use NumberFormat/DecimalFormat/(other?) to format when I don't know the Locale? According to the docs it will pick a default locale which won't work with a foreign Currency.


jsp - Formatting file sizes in Java/JSTL

This question already has answers here:


java printing on paper - formatting output for print

I have a java desktop application with information about several entities. There is a "print" button than WHEN pressed various information should be collected and printed. The question is: How can i select WHAT will be printed ON a specific location on the paper? A more general question would be: How can i format information to be printed on paper?






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top