简体   繁体   中英

Java xPath - extract subdocument from XML

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM