我有一个 XML 文档如下:
<DocumentWrapper>
<DocumentHeader>
...
</DocumentHeader>
<DocumentBody>
<Invoice>
<Buyer/>
<Seller/>
</Invoice>
</DocumentBody>
</DocumentWrapper>
我想从中提取 DocumentBody 元素的内容作为字符串,原始 XML 文档:
<Invoice>
<Buyer/>
<Seller/>
</Invoice>
使用 xPath 可以很容易地获得:
/DocumentWrapper/DocumentBody
不幸的是,我的 Java 代码不想按我的意愿工作。它返回空行而不是预期结果。是否有机会这样做,或者我必须返回 NodeList,然后从中生成 xml 文档?
我的 Java 代码:
XPathFactory xPathFactoryXPathFactory.newInstance();
XPath xPath xPathFactory.newXPath();
XPathExpression xPath.compile(xPathQuery);
String result = expression.evaluate(xmlDocument);
最佳答案
调用这个方法
String result = expression.evaluate(xmlDocument);
和调用这个是一样的
String result = (String) expression.evaluate(xmlDocument, XPathConstants.STRING);
返回结果节点的字符数据,如果结果节点是元素,则返回所有子节点的字符数据。
你可能应该这样做:
Node result = (Node) expression.evaluate(xmlDocument, XPathConstants.NODE);
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(result), new StreamResult(System.out));
关于Java xPath - 从 XML 中提取子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13217397/