使用具有Groovy的XMLParser读取XML [英] Read XML using XMLParser with groovy

查看:65
本文介绍了使用具有Groovy的XMLParser读取XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了以下XML类型,试图在其中使用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>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?

谢谢

推荐答案

您可以使用查找.见下文:

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

这篇关于使用具有Groovy的XMLParser读取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆