tags:

views:

162

answers:

2

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

Thanks

+4  A: 

You can do something like this:

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

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

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 section of the Groovy Docs for how to loop over XPath queries that will return multiple results:

http://docs.codehaus.org/display/GROOVY/Reading+XML+with+Groovy+and+XPath

tim_yates
Tim, thank you so much for your help. This has been a massive time-saver for me.
Jack
A: 

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 )
Jack