Java:XML 转换、文本节点中的换行符、中断缩进
我正在构建一个 XML 文档并使用 JVM 内置库将其打印为缩进格式。当文档中存在包含换行符的文本节点时,它会将行换行到行首,而不是正确的缩进位置
示例代码
ByteArrayOutputStream s;
s = new ByteArrayOutputStream();
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
Element a;
Text b;
a = d.createElement("a");
String text = "multi\nline\ntext";
b = d.createTextNode(text);
a.appendChild(b);
d.appendChild(a);
t.setOutputProperty(OutputKeys.INDENT,"yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(d), new StreamResult(s));
System.out.println(new String(s.toByteArray()));
输出
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>multi
line
text</a>
所需的输出
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
multi
line
text
</a>
是否有一种聪明的方法可以使每个新行从换行符的位置开始缩进的 xml 标签会开始吗?有人告诉我 textnode 不适合使用吗?还有更好的吗?
I'm building an XML document and printing out into an indented format using the JVM build-in libraries. When there is a text node in the document that contains a line break, it wraps the line to the start of the line instead of it's proper indented position
sample code
ByteArrayOutputStream s;
s = new ByteArrayOutputStream();
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
Element a;
Text b;
a = d.createElement("a");
String text = "multi\nline\ntext";
b = d.createTextNode(text);
a.appendChild(b);
d.appendChild(a);
t.setOutputProperty(OutputKeys.INDENT,"yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(d), new StreamResult(s));
System.out.println(new String(s.toByteArray()));
output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>multi
line
text</a>
desired output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
multi
line
text
</a>
Is there a smart way to make each new line begin at where the indented xml tag would begin? Something tells me textnode isn't the right thing to use? Is there something better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,更改缩进实际上会更改该节点的文本内容。 ie
将导致 XML api 读取的文本中出现多个前导空格。这就是你想要的吗?我知道这不是您问题的答案,但我不确定您是否真的想要保持缩进。您将如何处理在 XML 结构中进一步缩进的文本节点(即有更多的前导空格)?
Note that changing your indentation actually changes the text content of that node. i.e.
will result in multiple leading spaces in your text as read by XML apis. Is that what you want ? I know this isn't an answer to your question, but I'm not sure you really want to maintain indentation. How will you handle text nodes indented further down the XML structure (i.e. with many more leading spaces) ?