How to change JAXB Marshaller line separator?

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

I believe that the marshaller uses a system line separator.

 System.getProperty("line.separator") 

However, another escape sequence is required (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"); 
+6
source share
1 answer

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

 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.replace("\n", "\r\n"); 

To avoid any performance impact, you should set the approximate size (for example, 1024 -> 2 KB ) in the constructor for java.io.StringWriter .

+6
source

Source: https://habr.com/ru/post/953365/


All Articles