Java 如何更改 JAXB Marshaller 行分隔符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18668569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:00:38  来源:igfitidea点击:

How to change JAXB Marshaller line separator?

javafile-iojaxbmarshalling

提问by user2601995

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.

我相信编组员正在使用系统的行分隔符。

System.getProperty("line.separator")

However a different escape sequence is needed (i.e. \r\nneeds to be changed to \nor vice versa).

然而,需要不同的转义序列(即\r\n需要更改为\n,反之亦然)。

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

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

采纳答案by Paul Vargas

There is no a property that you can customize. Most implementationssend 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.

为避免对性能产生任何影响,您必须1024 -> 2 KB在构造函数中为设置近似大小(例如)java.io.StringWriter