首页 > 解决方案 > groovy xmlSlurper 检查同一级别内的更多字段

问题描述

我有这个xml。

<?xml version="1.0" encoding="utf-8"?>
<entry>
    <id>E0000</id>
    <link href="href">
        <inline>
            <entry>
                <link href="href">
                    <inline>
                        <feed>
                            <entry>
                                <id>E0001</id>
                                <content type="application/xml">
                                    <props>
                                        <status/>
                                    </props>
                                </content>
                            </entry>
                            <entry>
                                <id>E0002</id>
                                <content type="application/xml">
                                    <props>
                                        <status/>
                                    </props>
                                </content>
                            </entry>
                            <entry>
                                <id>E0003</id>
                                <content type="application/xml">
                                    <props>
                                        <status>S00</status>
                                    </props>
                                </content>
                            </entry>
                        </feed>
                    </inline>
                </link>
            </entry>
        </inline>
    </link>
</entry>

我正在使用 xmlSlurper 检查最深的“条目”标签中是否有一个同时具有“id”=“E0001”和“status”=“S00”或“id”=“E0002”和“status”=“S00” ”。像这样:(id=E0001 AND status=S00) OR (id=E0002 AND status=S00)。

我正在使用此代码(我正在使用 Groovy Web 控制台对其进行测试)。

    def text = '<?xml version=\"1.0\" encoding=\"utf-8\"?><entry><id>E0000</id><link href=\"href\"><inline><entry><link href=\"href\"><inline><feed><entry><id>E0001</id><content type=\"application/xml\"><props><status>S00</status></props></content></entry><entry><id>E0002</id><content type=\"application/xml\"><props><status/></props></content></entry><entry><id>E0003</id><content type=\"application/xml\"><props><status/></props></content></entry></feed></inline></link></entry></inline></link></entry>'
def response = new XmlSlurper().parseText(text)
def result = (response.link.inline.entry.link.inline.feed.find {(it.entry.content.props.status.text() == 'S00' & it.entry.id.text().contains('E0001')) | ((it.entry.content.props.status.text() == 'S00' & it.entry.id.text().contains('E0002')))}).size() > 0 ? 'true' : 'false'
println(result)

但是,即使 status=S00 位于 id=E0003 的“条目”标签下,结果也是如此,这是不需要的。我怎样才能调整我上面的代码?

标签: xmlgroovydoublenodesxmlslurper

解决方案


感谢克弗里克的建议。我已经对其进行了调整,并且可以正常工作。

def result = (response.link.inline.entry.link.inline.feed.entry.find {(it.content.props.status.text() == 'S00' & it.id.text().contains('E0001')) | ((it.content.props.status.text() == 'S00' & it.id.text().contains('E0002')))}).size() > 0 ? 'true' : 'false'

推荐阅读