[英]Groovy parse XML and get Value
I'm getting a XML responde like this: 我得到这样的XML响应:
xml = grails.converters.XML.parse( new URL( 'http://...) )
The XML is the following: 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>
And i want to store three things here: 我想在这里存储三件事:
<int name="QTime">272</int>
<str name="q">roger federer</str>
<result name="response" numFound="29327" start="0">
My output wud be: 我的输出是:
def one = '272'
def two = 'roger federer'
def three = '29327'
How can i accomplish that=? 我怎么能实现那个=? I would appreciate some help on this.
我将不胜感激。 Preferebly Groovy and not Java.
优选Groovy而不是Java。
One way of doing this might be: 这样做的一种方法可能是:
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
But it's a bit dependent on the xml being n the order you show for the findAll
to return things in the order required by the second bit 但它有点依赖于xml是你为
findAll
显示的顺序,以第二位所需的顺序返回东西
A more straight forward approach might be: 更直接的方法可能是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.