2017-02-26 123 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 ..”不起作用? –