2

Based on help from other questions I've asked, I've got this groovy snippet:

NodeList nodes = (NodeList)xpath.evaluate( xpathQuery, records, XPathConstants.NODESET );
return nodes.collect { node -> node.getTextContent() }

Which allows me to perform xpathQuery on records and get the result.

What I want to do now is just return (as a string) the raw xml of the result (rather than the text content) (I realise this will not result in a valid xml document).

Such that:

xml = "<root><apple><color>RED</color></apple>…</root>"
xpathQuery = "/root/apple[1]"

will return:

"<apple><color>RED</color></apple>"

(Without the enclosing <apple> tags would also be fine). Is there a simple way to do this?

Or failing that, is there another way to achieve this?

3
  • 1
    Depending on the XPath engine/API used, a returned XmlNode should have an outerXml property -- such as the .NET XmlNode type: msdn.microsoft.com/en-us/library/… Commented Jan 4, 2012 at 13:46
  • Or, if you are using XSLT, just use <xsl:copy-of> . Commented Jan 4, 2012 at 13:54
  • I'm using javax.xml.xpath which doesn't seem to have an outerXML property Commented Jan 4, 2012 at 17:56

1 Answer 1

1

This isn't very elegant, but could possibly be useful:

Use this:

concat('<apple><color>', //root/apple[1]/color, '</color></apple>')

If you know the structure won't change, or for a more complicated unknown number of child elements within <apple>, use:

//root/apple[1]/node() to give you all children nodes, and use groovy's .each function to iterate through the nodes, and create your string paddings, and combine them with the original //root/apple[1]/color result.

Sign up to request clarification or add additional context in comments.

Comments

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.