2017-02-26 110 views
0

我是groovy的新手。Groovy xml請求解析

試圖解析一些XML請求,沒有運氣一段時間。

至於最終結果:

  1. 我要檢查,如果XML請求 「RequestRecords」 有 「DetailsRequest」 atrribute;
  2. 獲得「FieldValue」號碼,其中「RequestF」具有FieldName =「Id」。

此外,由於某種原因,因爲它返回false爲 'DEF根=新XmlParser的()。parseText(XML)' 我不能使用的XmlSlurper。

def env = new groovy.xml.Namespace("http://schemas.xmlsoap.org/soap/envelope/", 'env'); 
def ns0 = new groovy.xml.Namespace("http://tempuri.org/", 'ns0') 

def xml = '''<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<env:Body> 
    <ns0:Request1> 
     <ns0:Request_Sub> 
      <ns0:RequestRecords TableName="Header"> 
       <ns0:RequestF FieldName="SNumber" FieldValue="XXX"/> 
       <ns0:RequestF FieldName="TNumber" FieldValue="30"/> 
      </ns0:RequestRecords> 
      <ns0:RequestRecords TableName="Details"> 
       <ns0:RequestF FieldName="Id" FieldValue="1487836040"/> 
      </ns0:RequestRecords> 
     </ns0:Request_Sub> 
     <ns0:isOffline>false</ns0:isOffline> 
    </ns0:Request1> 
</env:Body> 
</env:Envelope>''' 

def root = new XmlParser().parseText(xml) 

println ("root" + root) 

assert "root_node" == root.name() 
println root_node  

根節點即使斷言失敗。

回答

0

XmlSlurper或XmlParser應該可以正常工作。從我所看到的看來,它們在功能上似乎相當。它們僅在內存使用和性能方面有所不同。

它看起來像你從javadoc中的例子中複製了這段代碼,卻沒有意識到這些代碼塊的含義。顯然,「根節點」斷言失敗,因爲示例中根節點的名稱是「root_node」,但它是代碼中的「Envelope」。

不確定爲什麼你說XmlSlurper不起作用。你的代碼示例使用它甚至不使用它。

+0

那麼,正確的說法應該是在這種情況下? assert root.name()=='Envelope' 也失敗。 –

+0

在斷言之前添加'println'root [$ {root.name}]''以驗證它是什麼很容易。它爲我顯示了「信封」。 –

1

鑑於XML,你可以使用的XmlSlurper得到解答您的兩個問題,像這樣:

def root = new XmlSlurper().parseText(xml) 

// I want to check if xml request "RequestRecords" has "DetailsRequest" atrribute 
List<Boolean> hasAttribute = root.Body 
           .Request1 
           .Request_Sub 
           .RequestRecords 
           .collect { it.attributes().containsKey('DetailsRequest') } 
assert hasAttribute == [false, false] 

// Get "FieldValue" number where "RequestF" has FieldName="Id". 
String value = root.Body 
        .Request1 
        .Request_Sub 
        .RequestRecords 
        .RequestF 
        .find { [email protected] == 'Id' }[email protected] 

assert value == '1487836040' 
+0

如果我理解正確,「hasAttribute」應該返回true,如果找到短語,它總是返回false,例如搜索「Details」,「.containsKey('Details')。」 價值搜索工作 - 謝謝。 –

+0

任何建議,爲什麼「.collect {it.attributes()。containsKey ..」不起作用? –