Jack James Jack James - 1 year ago 170
Groovy Question

How do I create an XPath function in Groovy

I'm trying to create a function in Groovy that does the following:

  1. Accepts 2 parameters at runtime (a string of XML, and an xpath query)

  2. Returns the result as text

This is probably quite straightforward but for two obstacles:

  1. This has to be done in groovy

  2. 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)?


Answer Source

You can do something like this:

import javax.xml.xpath.*
import javax.xml.parsers.DocumentBuilderFactory

def testxml = '''
      <car name="HSV Maloo" make="Holden" year="2006">
        <record type="speed">Production Pickup Truck with speed of 271kph</record>

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
  xpath.evaluate( xpathQuery, records )

println processXml( testxml, '//car/record/@type' )

Have a look at this page (formerly part of the Groovy Docs) for how to loop over XPath queries that will return multiple results:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download