Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an XPath function in Groovy

Tags:

java

groovy

xpath

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

like image 557
Jack James Avatar asked Feb 15 '10 18:02

Jack James


People also ask

What is the function of XPath?

XPath is a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer.

What is XPath command?

XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.

What is XPath with examples?

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.


1 Answers

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 )
like image 185
Jack James Avatar answered Nov 01 '22 04:11

Jack James