简体   繁体   English

使用具有Groovy的XMLParser读取XML

[英]Read XML using XMLParser with groovy

I am having following type XML where I am trying to verify values in there using groovy. 我有以下类型的XML,我试图使用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

<?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>

Is there any other way to handle this? 还有其他方法可以解决吗?

Thanks 谢谢

You can use find . 您可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM