Groovy XML SLurper无法访问子节点

时间:2019-06-13 20:08:43

标签: groovy xmlslurper

我最近开始使用XML Slurper,并尝试从SOAP信封访问特定的子节点。以下是我正在使用的XML的一部分:

<cons:ConsumerName>
 <cons:FirstName>Robert</cons:FirstName>
 <cons:MiddleName>John</cons:MiddleName>
 <cons:FamilyName>Smith</cons:FamilyName>
</cons:ConsumerName>

<cons:ContactPersonName>
 <cons:FirstName>William</cons:FirstName>
 <cons:MiddleName>Michael</cons:MiddleName>
 <cons:FamilyName>Doe</cons:FamilyName>
</cons:ContactPersonName>

我正在尝试在ConusmerName块中访问FirstName的值,我只能使用以下方式获取两个名字值的列表:

def block = new XmlSlurper().parseText(text).'**'.findAll{it.name()=='FirstName'}

我尝试使用以下方法来仅获取ConsumerName块的名字:

def block = new XmlSlurper().parseText(text).'ConsumerName'.findAll{it.name()=='FirstName'}

但是那没有得到任何回报,我无法弄清楚我做错了什么吗?

2 个答案:

答案 0 :(得分:0)

我修复了您的xml并在此处提供了答案:

def text = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<cons:Consumer xmlns:cons="urn:corp:cons">' +
            '    <cons:ConsumerName>' +
            '        <cons:FirstName>Robert</cons:FirstName>' +
            '        <cons:MiddleName>John</cons:MiddleName>' +
            '        <cons:FamilyName>Smith</cons:FamilyName>' +
            '    </cons:ConsumerName>' +
            '' +
            '    <cons:ContactPersonName>' +
            '        <cons:FirstName>William</cons:FirstName>' +
            '        <cons:MiddleName>Michael</cons:MiddleName>' +
            '        <cons:FamilyName>Doe</cons:FamilyName>' +
            '    </cons:ContactPersonName>' +
            '</cons:Consumer>'

    def consumer = new XmlSlurper().parseText(text)

    println "Consumer first name: ${consumer.ConsumerName.FirstName}"

输出:

Consumer first name: Robert

答案 1 :(得分:0)

要在XML的ConsumerName块中获取firstName值,我使用了以下内容:

def text = new File(requestFilePath).text
def fieldValue = new XmlSlurper().parseText(text).'**'.findAll{it.name()==tagBlockName}.getAt(tagName)[0]
def var = (String)fieldValue