Groovy XML请求解析



我是Groovy的新手。

试图解析一些XML请求,一段时间没有运气。

作为最终结果:

  1. 我想检查XML请求" RequestRecords"是否具有"详细信息"
  2. 获取" fieldValue"号码,其中" requestf"具有fieldName =" id"。

另外,由于某些原因,我无法使用XMLSlurper,因为它返回false tof to'def root = new xmlparser()。parsetext(xml)'。

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    

甚至root节点的断言失败。

鉴于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 { it.@FieldName == 'Id' }?.@FieldValue
assert value == '1487836040'

XMLSlurper或XMLPARSER应该可以正常工作。从我所看到的,它们在功能上似乎是等效的。它们仅在内存使用和性能方面有所不同。

看起来您从Javadoc中的示例复制了此代码,而没有意识到某些作品的含义。显然," root节点"的断言失败了,因为该示例的root节点的名称是" root_node",但它是您的代码中的"信封"。

不确定您为什么要说XMLSlurper不起作用。您的代码示例甚至都不使用。

最新更新