我正在尝试从 XML 节点创建格式化字符串。请参阅此示例:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<parent>
<foo>
<bar>foo</bar>
</foo>
</parent>
</root>
我想要为其创建格式化字符串的节点是“foo”。我期望的结果是这样的:
<foo>
<bar>foo</bar>
</foo>
但实际结果是:
<foo>
<bar>foo</bar>
</foo>
我的方法如下:
public String toXmlString(Node node) throws TransformerException {
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
final Writer writer = new StringWriter();
final StreamResult streamResult = new StreamResult(writer);
transformer.transform(new DOMSource(node), streamResult);
return writer.toString();
}
我做错了什么?
最佳答案
它正在做它应该做的事情。 indent="yes"
允许转换添加空格来缩进元素,但不能删除空格,因为它无法知道输入中的哪个空格是重要的。
在您提供的输入中,<foo>
和</foo>
元素行有 8 个前导空格,并且 <bar>
行有 12 个。
原因<foo>
开始标记未缩进的原因是前面的空格实际上属于包含 <parent>
元素并且不存在于您传递给转换的子树中。
标准中详细介绍了空白剥离行为( XSLT 1 、 XSLT 2 )。总结
A whitespace text node is preserved if either of the following apply:
- The element name of the parent of the text node is in the set of whitespace-preserving element names
- ...
和
(XSLT 2) The set of whitespace-preserving element names is specified by xsl:strip-space and xsl:preserve-space declarations. Whether an element name is included in the set of whitespace-preserving names is determined by the best match among all the xsl:strip-space or xsl:preserve-space declarations: it is included if and only if there is no match or the best match is an xsl:preserve-space element.
XSLT 1 规范中有更简单的说明:
Initially, the set of whitespace-preserving element names contains all element names.
不幸的是,使用 xsl:strip-space
不会产生您想要的结果。与<xsl:strip-space elements="*">
(和 indent="yes"
)我得到以下输出:
<foo><bar>foo</bar>
</foo>
这是有道理的。空格被删除,然后 </foo>
标签在其开始标签下对齐。
关于java - 如何从java中的xml节点创建格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51490749/