Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

http://groovy.jmiguel.eu/groovy.codehaus.org/Reading+XML+with+Groovy+and+XPath.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...