2014-10-17 56 views
0

我有以下类型的XML,我试图验证那里使用groovy值。使用XMLParser阅读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>[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> 

是否有任何其他的方式来处理呢?

谢谢

回答

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

感谢堆。我能够使用'value.text()'验证其他值。也许我应该增加我的思维能力。 – SMPH 2014-10-17 06:28:36

+0

:)不客气! – Opal 2014-10-17 06:41:11

+0

只需澄清一下,是否可以验证元素值,例如' 342ADC23-DC59'正在属于'eventType =“updateAddress”'的事件下。因为可能有可能出现在不同的eventType下。 – SMPH 2014-10-18 05:57:17