本文介绍了如何控制javax.xml.transform.Transformer创建的行结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在使用以下方法将DOM文档(org.w3c.dom.Document)转换为流I am transforming a DOM document (org.w3c.dom.Document) to a Stream usingTransformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.ENCODING, UTF_8.name());ByteArrayOutputStream out = new ByteArrayOutputStream();StreamResult output = new StreamResult(out);Source input = new DOMSource(document);transformer.transform(input, output);文档包含带有换行符('\n')的文本节点。在输出中,将替换为CRLF( \r\n),这是不希望的。有没有办法控制它(当然,之后还要替换它们)?The document contains text nodes with linefeeds ('\n'). In the output theyare replaced with CRLF ("\r\n"), which is not desired. Is there a way to control this (besides replacing them afterwards, of course)?我无法控制文档DTD(-> XML空格处理)。I have no control over the documents DTD (-> XML whitespace handling).(备注:OutputKeys.INDENT不是正确的答案。)(Remark: OutputKeys.INDENT is not the correct answer.)备注:为什么这个问题与问题19102804(确保Unix风格:Remark: Why this question is different from question 19102804 (Ensure Unix-style line endings): 这个问题明确地指向javax.xml.transform.Transformer以及影响其对行尾的处理。问题19102804要求提供任何解决方案,不仅是使用javax.xml.transform.Transformer的解决方案。This question refers explicitely to javax.xml.transform.Transformer and to the possibilities to influence its treatment of line endings. Question 19102804 asks for any solution, not only for one using javax.xml.transform.Transformer.问题19102804仅限于获得 Unix-样式行结尾。在我的情况下,理想的解决方案是将组件按原样放出DOM模型实例,而不接触任何节点(到目前为止所做的一切)。Question 19102804 is limited to the task of getting "Unix-style line endings". In my case the ideal solution would be a component that justs puts out the DOM model instance as it is, not touching any node (what everything so far does).不能更改line.separator系统属性(请参见评论)。Changing the line.separator system property is not an option (see comment).推荐答案如果您要做的只是序列化DOM节点,那么在Java世界中,您可以使用 LSSerializer ( https://docs.oracle.com/javase/7/docs/api/org /w3c/dom/ls/LSSerializer.html ),而不是默认的 Transformer ,然后您便有了方法 setNewLine ( https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/LSSerializer.html#setNewLine(java.lang.String))进行定义或控制您的偏好结束。If all you want to do is serialize a DOM node then in the Java world you can use LSSerializer (https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/LSSerializer.html) instead of a default Transformer and then you have the method setNewLine (https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/LSSerializer.html#setNewLine(java.lang.String)) to define or control your preferred line ending. 这篇关于如何控制javax.xml.transform.Transformer创建的行结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-14 15:14