Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jaxb

moxy

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?

like image 626
Thang Pham Avatar asked Mar 06 '12 19:03

Thang Pham


Video Answer


2 Answers

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

  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

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.

  • https://stackoverflow.com/a/3625359/383861
like image 54
bdoughan Avatar answered Oct 05 '22 21:10

bdoughan


Inspired by first option of bdoughan's comment in this post, I've written a custom writer to remove blank line in xml file like the following ways:

public class XmlWriter extends FileWriter {

    public XmlWriter(File file) throws IOException {
        super(file);
    }

    public void write(String str) throws IOException {
        if(org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
            super.write(str);
        }
    }
}

To check empty line, I've used org.apache.commons.lang3.StringUtils.isNotBlank() method, you can use your own custom condition.

Then use this writer to marshal method like the following way in Java 8.

// skip other code
File file = new File("test.xml");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
try (FileWriter writer = new XmlWriter(file)) {
    marshaller.marshal(object, writer);
}

It'll remove <?xml version="1.0" encoding="UTF-8" standalone="yes"?> tag, also will not print blank line.

like image 39
arifng Avatar answered Oct 05 '22 20:10

arifng