Groovy解析XML和获取属性

时间:2013-03-18 11:38:27

标签: 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

我犯了错误?

提前致谢。

1 个答案:

答案 0 :(得分: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 { it.@name == 'ttype' }?.text(),
    r.find { it.@name == 'tempTxnId' }?.text() ]
}

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