title: How do I create an XPath function in Groovy
body: <p>I'm trying to create a function in Groovy that does the following:</p>
  
  <ol>
  <li>Accepts 2 parameters at runtime (a string of XML, and an xpath query)</li>
  <li>Returns the result as text</li>
  </ol>
  
  <p>This is probably quite straightforward but for two obstacles:</p>
  
  <ol>
  <li>This has to be done in groovy</li>
  <li>I know next to nothing nothing about groovy or Java…</li>
  </ol>
  
  <p>This is as far as I've got by hacking various bits of code together, but now I'm stuck:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>where "xml" and "expression" are runtime parameters. How do I get this now to return the result (as a string)?</p>
  
  <p>Thanks</p>