2

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 Answer 1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

XMLConstants.NODE does not look valid any more.
@takias True! XMLConstants -> XPathConstants

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.