Groovy中解析XML和获取属性
问题描述:
我有一个这样的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>
我怎么能得到的ttype
和tempTxnId
值。我试过了:
def details = new XmlParser().parseText(response)
details.MMP.RESPONSE //which returns the whole xml itself rather than its contents
我在哪里犯错?
在此先感谢。
答
给出:
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'