2011-12-07 110 views
1

我得到一個XML responde這樣的:Groovy中解析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"> 

我的輸出WUD是:

def one = '272' 
def two = 'roger federer' 
def three = '29327' 

我該怎麼做到=?我將不勝感激這方面的一些幫助。優先考慮Groovy而不是Java。

回答

4

這樣做可能是一個辦法:

xml = grails.converters.XML.parse(new URL('http://...)) 

def (one, two, three) = xml.depthFirst().findAll { 
    [email protected] == 'QTime' || [email protected] == 'q' || [email protected] == 'response' 
}.with { a, b, c -> 
    [ a.text(), b.text(), [email protected] ] 
} 

println one 
println two 
println three 

但它是一個有點依賴於XML爲N您展示了findAll順序在第二位所需的順序返回的東西

更直接的做法可能是:

def one = xml.lst.int.find { [email protected] == 'QTime' }.text() 
def two = xml.lst.lst.str.find { [email protected] == 'q' }.text() 
def three = [email protected] 

println one 
println two 
println three