【发布时间】:2018-12-03 14:51:14
【问题描述】:
How to control line endings that javax.xml.transform.Transformer creates? 的评论建议设置系统属性“line.separator”。这在 Java 8(Oracle JDK 1.8.0_171)中对我有用(并且对于我手头的任务是可以接受的),但在 Java 11(openjdk 11.0.1)中却不行。
从票 XALANJ-2137 我做了一个(未受过教育,因为我什至不知道我正在使用哪个 javax.xml 实现)猜测尝试 setOutputProperty("{http://xml.apache.org/xslt}line-separator", ..) 或 setOutputProperty("{http://xml.apache.org/xalan}line-separator", ..),但两者都不起作用。
如何在 Java 11 中控制转换器的换行符?
这里有一些演示代码,在带有 Java 11 的 Windows 下打印“... #13 #10 ...”,它应该只打印“... #10 ...”。
package test.xml;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.stream.Collectors;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class TestXmlTransformerLineSeparator {
public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><foo/></root>";
final String lineSep = "\n";
String oldLineSep = System.setProperty("line.separator", lineSep);
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", lineSep);
transformer.setOutputProperty("{http://xml.apache.org/xslt}line-separator", lineSep);
StreamSource source = new StreamSource(new StringReader(xml));
StringWriter writer = new StringWriter();
StreamResult target = new StreamResult(writer);
transformer.transform(source, target);
System.out.println(writer.toString().chars().mapToObj(c -> c <= ' ' ? "#" + c : "" + Character.valueOf((char) c))
.collect(Collectors.joining(" ")));
System.out.println(writer);
} finally {
System.setProperty("line.separator", oldLineSep);
}
}
}
【问题讨论】:
-
我刚刚遇到了同样的问题。有没有运气解决这个问题?
-
很遗憾没有。
标签: java xml pretty-print