0
votes

Assuming some xml like

<foo>
  <bar>test</bar>
</foo>

Evaluating an expression with returnType = String like

/foo/bar

will return "test". However, I'd like to get the serialized xml instead, so something like

<bar>test</bar>

should be returned instead. As I can not check for the returnType in java's xpath implementation (xerces), I cannot simply get an object as result and if it indeed is a node, convert it to serialized xml.

Note: I don't know whether the expression will actually return a node, a string, a number or whatever so I cannot provide an appropriate return type to the eval function except string which, as my problem states, returns the text content and not the serialized xml.

So I am curious -> is there either a java- or (preferred) a xpath-way (function?) to get serialized xml for type string instead of the text children of the selected node?

thanks! Alex

3

3 Answers

1
votes

use the xpath return type XPathConstants.NODE and then you can serialize the returned Node yourself.

0
votes

Now, you are right to observe that it's difficult to discover the return type of the result; this is a real design weakness of JAXP.

If it's a problem to you, consider using Saxon's s9api interface, which returns XdmValue objects whose type you can interrogate; you also get XPath 2.0 access as a bonus.

0
votes

As Michael Kay answered, this is difficult in JAXP (the native Java interface).

In Mr Kay's Saxon library's s9api API (see Evaluating XPath Expressions using s9api), once you've called XPathSelector.evaluate() or XPathSelector.evaluateSingle() you can get the XML serialisation by calling XdmValue.toString().

However, if the XPath selected an attribute (e.g. //@name) you will still get the XML serialisation, e.g. name="value". You can call XdmItem.getStringValue(), but for elements that method will return the same values you're already seeing - the textual content of the element, not the serialisation. I've posted separately about how to distinguish between attributes and elements returned from Saxon s9api.