Java xPath - extract subdocument from XML

你说的曾经没有我的故事 提交于 2019-12-08 01:39:00

问题


I have an XML document as follows:

<DocumentWrapper>
  <DocumentHeader>
    ...
  </DocumentHeader>
  <DocumentBody>
    <Invoice>
      <Buyer/>
      <Seller/>
    </Invoice>
   </DocumentBody>
 </DocumentWrapper>

I would like to extract from it the content of DocumentBody element as String, raw XML document:

<Invoice>
  <Buyer/>
  <Seller/>
</Invoice>

With xPath it could be simple to get by:

/DocumentWrapper/DocumentBody

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?

My Java code:

XPathFactory xPathFactoryXPathFactory.newInstance();
XPath xPath xPathFactory.newXPath();
XPathExpression xPath.compile(xPathQuery);

String result = expression.evaluate(xmlDocument);

回答1:


Calling this method

String result = expression.evaluate(xmlDocument);

is the same as calling this

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));


来源:https://stackoverflow.com/questions/13217397/java-xpath-extract-subdocument-from-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!