2013-03-18 170 views
0

我有一個這樣的XML:Groovy中解析XML和獲取屬性

<MMP> 
<MERCHANT> 
<RESPONSE> 
<url>http://203.114.240.77/paynetz/epi/fts</url> 
<param name="ttype"></param> 
<param name="tempTxnId"></param> 
</RESPONSE> 
</MERCHANT> 
</MMP> 

我怎麼能得到的ttypetempTxnId值。我試過了:

def details = new XmlParser().parseText(response) 
details.MMP.RESPONSE //which returns the whole xml itself rather than its contents 

我在哪裏犯錯?

在此先感謝。

回答

5

給出:

def response = '''<MMP> 
       | <MERCHANT> 
       | <RESPONSE> 
       |  <url>http://203.114.240.77/paynetz/epi/fts</url> 
       |  <param name="ttype">a</param> 
       |  <param name="tempTxnId">b</param> 
       | </RESPONSE> 
       | </MERCHANT> 
       |</MMP>'''.stripMargin() 

然後:

def (ttype,tempTxn) = new XmlParser().parseText(response) 
            .MERCHANT.RESPONSE.param.with { r -> 
    [ r.find { [email protected] == 'ttype' }?.text(), 
    r.find { [email protected] == 'tempTxnId' }?.text() ] 
} 

assert ttype == 'a' 
assert tempTxn == 'b'