Java xPath-从XML提取子文档 [英] Java xPath - extract subdocument from XML
问题描述
我有一个XML文档,如下所示:
I have an XML document as follows:
<DocumentWrapper>
<DocumentHeader>
...
</DocumentHeader>
<DocumentBody>
<Invoice>
<Buyer/>
<Seller/>
</Invoice>
</DocumentBody>
</DocumentWrapper>
我想从其中提取DocumentBody元素的内容作为String(原始XML文档):
I would like to extract from it the content of DocumentBody element as String, raw XML document:
<Invoice>
<Buyer/>
<Seller/>
</Invoice>
使用xPath可能很容易获得:
With xPath it could be simple to get by:
/DocumentWrapper/DocumentBody
毫无疑问,我的Java代码不想按我希望的那样工作.它返回空行而不是预期的结果.有没有机会这样做,还是我必须返回NodeList然后从它们中生成xml文档?
Unfrotunatelly, my Java code doesn't want to work as I want. It returns empty lines instead of expected result. Is there any chance to do that, or I have to return NodeList and then genereate xml document from them?
我的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);
返回结果节点的字符数据,或者如果结果节点是元素,则返回所有子节点的字符数据.
which returns the character data of the result node, or the character data of all child nodes in case the result node is an element.
您可能应该执行以下操作:
You should probably do something like this:
Node result = (Node) expression.evaluate(xmlDocument, XPathConstants.NODE);
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(result), new StreamResult(System.out));
这篇关于Java xPath-从XML提取子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!