如何在 Groovy 中创建 XPath 函数 [英] How do I create an XPath function in Groovy
问题描述
我正在尝试在 Groovy 中创建一个执行以下操作的函数:
I'm trying to create a function in Groovy that does the following:
- 在运行时接受 2 个参数(一个 XML 字符串和一个 xpath 查询)
- 以文本形式返回结果
这可能很简单,但有两个障碍:
This is probably quite straightforward but for two obstacles:
- 这必须在 groovy 中完成
- 我对 groovy 或 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)
其中xml"和表达式"是运行时参数.我现在如何获得它以返回结果(作为字符串)?
where "xml" and "expression" are runtime parameters. How do I get this now to return the result (as a string)?
谢谢
推荐答案
你可以这样做:
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' )
查看此页面(以前是 Groovy Docs 的一部分)了解如何循环返回多个结果的 XPath 查询:
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
这篇关于如何在 Groovy 中创建 XPath 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!