Shabar
Shabar

Reputation: 2811

Read XML using XMLParser with groovy

I am having following type XML where I am trying to verify values in there using groovy.

I tried below code. But the problem is the order of events we cannot predict in advance. So following code is failing due to that issue.

def records = new XmlParser().parseText(eventFile)

assert "emailId" == records.Event.eventAttributes.EventAttribute.getAt(0).name.text()
assert emailId == records.Event.eventAttributes.EventAttribute.getAt(0).value.text()
assert "userId" == records.Event.eventAttributes.EventAttribute.getAt(1).name.text()
assert consumerID == records.Event.eventAttributes.EventAttribute.getAt(1).value.text()

XML:

<?xml version="1.0" encoding="UTF-8"?>
<SystemEvents feedtime="04:17:37" feeddate="20141017" version="0.0.0.2">
<Event id="7ecef115-7a09-406d" name="registration" eventType="registration">
    <eventTime>2014-10-17T04:17:36Z</eventTime>
    <eventAttributes>
      <EventAttribute>
        <name>emailId</name>
        <value>[email protected]</value>
      </EventAttribute>
      <EventAttribute>
        <name>userId</name>
        <value>47C45983-0E03</value>
      </EventAttribute>
    </eventAttributes>
  </Event>
  <Event id="83157ddc-1500" name="updateAddress" eventType="updateAddress">
    <eventTime>2014-10-17T04:17:19Z</eventTime>
    <eventAttributes>
      <EventAttribute>
        <name>userId</name>
        <value>342ADC23-DC59</value>
      </EventAttribute>
      <EventAttribute>
        <name>ProfileNo</name>
        <value>123141017151658</value>
      </EventAttribute>
    </eventAttributes>
  </Event>
 // more tags
</SystemEvents>

Is there any other way to handle this?

Thanks

Upvotes: 0

Views: 424

Answers (1)

Opal
Opal

Reputation: 84756

You can use find. See below:

def email = records.Event.eventAttributes.EventAttribute.find { it.name.text() == 'emailId' }
assert 'emailId' == email.name.text()
def user = records.Event.eventAttributes.EventAttribute.find { it.name.text() == 'userId' }
assert 'userId' == user.name.text()

Upvotes: 2

Related Questions