JAXB: Marshal output XML with indentation create empty line break on the first line

Thang Pham picture Thang Pham · Mar 6, 2012 · Viewed 13.8k times · Source

When I marshal an XML with this attribute

marshal.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

it will generate an empty line break at the very top

//Generate empty line break here    
<XX>
    <YY>
        <PDF>pdf name</PDF>
        <ZIP>zip name</ZIP>
        <RECEIVED_DT>received date time</RECEIVED_DT>
    </YY>
</XX>

I think the reason is because marshal.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);, which remove <?xml version="1.0" encoding="UTF-8" standalone="yes"?>, leave the output xml a line break in the beginning. Is there a way to fix this? I use JAXB come with JDK 6, does Moxy suffer from this problem?

Answer

bdoughan picture bdoughan · Mar 7, 2012

As you point out EclipseLink JAXB (MOXy) does not have this problem so you could use that (I'm the MOXy lead):

Option #1

One option would be to use a java.io.FilterWriter or java.io.FilterOutputStream and customize it to ignore the leading new line.

Option #2

Another option would be to marshal to StAX, and use a StAX implementation that supports formatting the output. I haven't tried this myself but the answer linked below suggests using com.sun.xml.txw2.output.IndentingXMLStreamWriter.