简体   繁体   English

确保在使用Java在Windows上生成XML时使用的Unix样式行结尾

[英]Ensure Unix-style line endings used when generating XML on Windows with Java

I am currently outputting an XML document to a file in Java as follows: 我目前正在使用Java将XML文档输出到文件中,如下所示:

final Document xmldoc = toXMLDocument(docTheory);

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(xmldoc);
StreamResult result = new StreamResult(file);

transformer.transform(source, result);

However, when run on Windows, this produces output with Windows-style line-endings. 但是,在Windows上运行时,会生成带有Windows样式的行结尾的输出。 I would like to have Unix-style line endings produced regardless of OS. 我希望无论操作系统如何都能生成Unix风格的行结尾。 How I can do this? 我怎么能这样做?

The difference between operating systems is because it is used internally the method println . 操作系统之间的区别是因为它在内部使用了println方法。 Before saving the file, change the line separator: 在保存文件之前,请更改行分隔符:

System.setProperty("line.separator", "\n");

You could use a static block. 您可以使用静态块。

Unsure if the classes you're using use the system properties, but if they do, this should work 不确定您使用的类是否使用系统属性,但如果它们使用,则应该可以使用

System.setProperty("line.separator", "\n");

Related question but for Windows line endings 相关问题,但适用于Windows行结尾

If not, you'll have to do as Foo Bar User said in his comment, replace them manually. 如果没有,你将不得不像Foo Bar User在他的评论中所说,手动更换它们。

如果使用LSSerializer而不是Transformer,则可以使用LSSerializer.setNewLine来控制换行符。

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

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