2014-10-17 70 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