I’m trying to create a function in Groovy that does the following:
- Accepts 2 parameters at runtime (a string of XML, and an xpath query)
- Returns the result as text
This is probably quite straightforward but for two obstacles:
- This has to be done in groovy
- I know next to nothing nothing about groovy or Java…
This is as far as I’ve got by hacking various bits of code together, but now I’m stuck:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(new ByteArrayInputStream(xml.bytes));
expr = XPathFactory.newInstance().newXPath().compile(expression);
Object result = expr.evaluate(doc, XPathConstants.NODESET)
where “xml” and “expression” are runtime parameters. How do I get this now to return the result (as a string)?
Thanks
You can do something like this:
Have a look at this page (formerly part of the Groovy Docs) for how to loop over XPath queries that will return multiple results:
http://groovy.jmiguel.eu/groovy.codehaus.org/Reading+XML+with+Groovy+and+XPath.html