batman
batman

Reputation: 4908

Groovy Parsing XML and Get Attributes

I have an xml like this:

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

how can I get the values of ttype and tempTxnId. I tried:

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

where I'm making the mistake?

Thanks in advance.

Upvotes: 0

Views: 2616

Answers (1)

tim_yates
tim_yates

Reputation: 171074

given:

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()

Then:

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'

Upvotes: 5

Related Questions