Java xPath - extract subdocument from XML

2019-05-28 10:44发布

问题:

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