Groovy gpath 在与前缀 xml 标签一起使用时不起作用

Groovy gpath not working when used with prefixed xml tags

我在使用 gpath 时遇到一些命名空间问题。

String record = '''
    <u:record>
        <u:controlfield tag="001">017003167</u:controlfield>
        <u:datafield ind2="" ind1="" tag="Tag_1234">
            <u:subfield code="a">Peter</u:subfield>
            <u:subfield code="b">10</u:subfield>
        </u:datafield>  
        <u:datafield ind2="" ind1="" tag="Tag_1234">
            <u:subfield code="a">Simon</u:subfield>
            <u:subfield code="b">20</u:subfield>
        </u:datafield>  
        <u:datafield ind2="" ind1="" tag="Tag_20">
            <u:subfield code="a">Simon</u:subfield>
            <u:subfield code="b">20</u:subfield>
        </u:datafield>          
    </u:record>
    '''

GPathResult studentRecord = new XmlSlurper(false, false).parseText(record)
GPathResult filteredRecord = studentRecord.datafield.findAll { it.'@tag' == 'Tag_1234' } 

println "filteredRecord: ${filteredRecord}\n"
println "filteredRecord size is ${filteredRecord.size()}\n"

输出为0。不知道为什么。如果我删除 xml 前缀 "u:" gpath 工作正常。谁能告诉我哪里出错了。

试试这个:

def studentRecord = new XmlSlurper(false, false).parseText(record)
def filteredRecord = studentRecord.'u:datafield'.findAll { it.'@tag' == 'Tag_1234' }