简体   繁体   English

如何更改JAXB Marshaller行分隔符?

[英]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)? 什么属性用于更改Marshaller( javax.xml.bind.Marshaller )行分隔符(回车符,换行符,换行符)?

I believe the marshaller is using the systems's line separator. 我相信marshaller正在使用系统的行分隔符。

System.getProperty("line.separator")

However a different escape sequence is needed (ie \\r\\n needs to be changed to \\n or vice versa). 但是需要不同的转义序列(即\\r\\n需要更改为\\n ,反之亦然)。

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.setProperty("line.separator", "\r\n");

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 (eg 1024 -> 2 KB ) in the constructor for java.io.StringWriter . 为避免对性能产生任何影响,必须在java.io.StringWriter的构造函数中设置近似大小(例如1024 -> 2 KB )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM