我得到这样的XML响应:
xml = grails.converters.XML.parse( new URL( 'http://...) )
XML如下:
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">272</int>
<lst name="params">
<str name="indent">on</str>
<str name="start">0</str>
<str name="q">roger federer</str>
<str name="version">2.2</str>
<str name="rows">10</str>
</lst>
</lst>
<result name="response" numFound="29327" start="0">
<doc>
<str name="id">135350</str>
<int name="revision">723055</int>
<date name="timestamp">2005-08-21T22:34:05Z</date>
<str name="title">Federer</str>
<str name="titleText">Federer</str>
<str name="user">Indech</str>
<str name="userId">3073</str>
</doc>
<doc>...</doc>
...
<doc>...</doc>
</result>
</response>
我想在这里存储三件事:
<int name="QTime">272</int>
<str name="q">roger federer</str>
<result name="response" numFound="29327" start="0">
我的输出是:
def one = '272'
def two = 'roger federer'
def three = '29327'
我怎样才能实现=?我将不胜感激。优选Groovy而不是Java。
答案 0 :(得分:4)
这样做的一种方法可能是:
xml = grails.converters.XML.parse( new URL( 'http://...) )
def (one, two, three) = xml.depthFirst().findAll {
it.@name == 'QTime' || it.@name == 'q' || it.@name == 'response'
}.with { a, b, c ->
[ a.text(), b.text(), c.@numFound ]
}
println one
println two
println three
但它有点依赖于xml是你显示的顺序findAll
以第二位所需的顺序返回事物
更直接的方法可能是:
def one = xml.lst.int.find { it.@name == 'QTime' }.text()
def two = xml.lst.lst.str.find { it.@name == 'q' }.text()
def three = xml.result.@numFound
println one
println two
println three