迭代所有Xpath结果
我有以下代码:迭代所有Xpath结果,xpath,groovy,xpathquery,Xpath,Groovy,Xpathquery,我有以下代码: #!/usr/bin/groovy import javax.xml.xpath.* import javax.xml.parsers.DocumentBuilderFactory def testxml = ''' <Employee> <ID>..</ID> <E-mail>..</E-mail>
#!/usr/bin/groovy
import javax.xml.xpath.*
import javax.xml.parsers.DocumentBuilderFactory
def testxml = '''
<Employee>
<ID>..</ID>
<E-mail>..</E-mail>
<custom_1>foo</custom_1>
<custom_2>bar</custom_2>
<custom_3>base</custom_3>
</Employee>
'''
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, '//*[starts-with(name(), "custom")]' )
#/usr/bin/groovy
导入javax.xml.xpath*
导入javax.xml.parsers.DocumentBuilderFactory
def testxml=''
..
..
福
酒吧
基础
'''
def processXml(字符串xml、字符串xpathQuery){
def xpath=XPathFactory.newInstance().newXPath()
def builder=DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream=new ByteArrayInputStream(xml.bytes)
def records=builder.parse(inputStream.documentElement)
evaluate(xpathQuery,记录)
}
println processXml(testxml,'/*[以(name(),“custom”)]开头])
而不是返回所有节点(我在Xpath表达式中提供了/
),我只得到第一个节点。如何修改代码以显示所有匹配的节点?根据您传递的文档评估所需内容,默认为字符串。因此,请求节点集:
xpath.evaluate( xpathQuery, records, XPathConstants.NODESET )
并迭代生成的节点列表
:
def result = processXml( testxml, '//*[starts-with(name(), "custom")]' )
result.length.times{
println result.item(it).textContent
}
谢谢,如果你能把整个过程缩短,我很感兴趣;)