使用带有groovy的XMLParser读取XML

时间:2014-10-17 05:33:56

标签: xml groovy

我正在使用以下类型的XML,我正在尝试使用groovy验证其中的值。

我试过下面的代码。但问题是我们无法提前预测的事件顺序。所以下面的代码由于这个问题而失败。

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>d2bcon_s141017151735@trashcanmail.com</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>

还有其他方法可以解决这个问题吗?

由于

1 个答案:

答案 0 :(得分:2)

您可以使用find。见下文:

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