我使用 xpath 来获取 NodeList。然后我使用此代码来获取字符串表示形式,但它也具有父节点。
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException e) {
e.printStackTrace();
}
return sw.toString();
我怎样才能只获取 self 或后代作为字符串?也许还可以从父级窃取命名空间声明?
最佳答案
您没有显示如何选择节点集中的节点。它们很可能是元素,这就是您的问题的原因。
解决方案很简单:
构造并使用仅选择所需文本节点的 XPath 表达式。
例如,代替:
/x/y/z
使用
/x/y/z/text()
最后一个表达式选择作为任何名为 z
的元素的子级的任何文本节点,该元素又是名为 y
的任何元素的子级,而该元素又是名为 x
的顶部元素的子级。
更新:
OP 在评论中澄清了:
"Thanks, I tried this, but it only gives my real text in node. I want a string reresentation of everything (nodes and text) in the current node, without the information of the parent nodes. E.g if I would just have a xml file and open it with a text editor and then copy out some subtree. Do you know what I'm talking about?"
这可以在 XSLT 中使用
来完成<xsl:copy-of select="yourExpression/node()"/>
或者,如果您的 XML API 允许,则对于每个选定的节点使用:
theSelectedNode.InnerXml
关于java - 没有父信息的节点到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7617157/