Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change JAXB Marshaller line separator?

What property is used to change the Marshaller (javax.xml.bind.Marshaller) line separator (carriage return, new line, line break)?

I believe the marshaller is using the systems's line separator.

System.getProperty("line.separator")

However a different escape sequence is needed (i.e. \r\n needs to be changed to \n or vice versa).

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.setProperty("line.separator", "\r\n");
like image 708
user2601995 Avatar asked Sep 07 '13 00:09

user2601995


People also ask

What is Marshaller in JAXB?

The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling to XML can be done to variety of output targets.

How does JAXB marshalling work?

In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.

What is Java Marshaller?

public interface Marshaller. The Marshaller class is responsible for governing the process of serializing Java content trees back into XML data.


1 Answers

There is no a property that you can customize. Most implementations send directly to the buffer the line separator:

write('\n');

However, you can replace the result.

Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

StringWriter writer = new StringWriter(1024); // 2 KB
marshaller.marshal(obj, writer);

String str = writer.toString();
str = str.replaceAll("\r?\n", "\r\n");  // only convert if necessary

To avoid any effect on the performance, you must set the approximate size (e.g. 1024 -> 2 KB) in the constructor for java.io.StringWriter.

like image 170
Paul Vargas Avatar answered Oct 04 '22 06:10

Paul Vargas