I'm trying to create a function in Groovy that does the following:
This is probably quite straightforward but for two obstacles:
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
XPath is a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer.
XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.
XPath is a major element in the XSLT standard. XPath can be used to navigate through elements and attributes in an XML document. XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath contains a library of standard functions.
This was what I eventually settled for, which should work for my purposes:
import javax.xml.xpath.*
import javax.xml.parsers.DocumentBuilderFactory
def processXml( String xml, String xpathQuery ) {
def xpath = XPathFactory.newInstance().newXPath()
def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream( xml.bytes )
def records = builder.parse(inputStream).documentElement
def nodes = xpath.evaluate( xpathQuery, records, XPathConstants.NODESET )
nodes.collect { node -> node.textContent }
}
processXml( xml, query )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With