我有这段代码:
#!/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")]' )
而不是返回所有节点(我在Xpath表达式中提供//
),我只得到第一个节点。如何修改我的代码以显示所有匹配的节点?
答案 0 :(得分:2)
根据文档http://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.html,您传递了evaluate
您想要的内容,默认为字符串。所以请求NODESET:
xpath.evaluate( xpathQuery, records, XPathConstants.NODESET )
并迭代生成的NodeList
:
def result = processXml( testxml, '//*[starts-with(name(), "custom")]' )
result.length.times{
println result.item(it).textContent
}