【问题标题】:How would I find the text of a node that has a specific value for an attribute in groovy?如何在 groovy 中找到具有特定属性值的节点的文本?
【发布时间】:2012-03-31 09:00:24
【问题描述】:

我正在使用 XMLSlurper。我的代码在下面(但不起作用)。问题是当它碰到一个没有属性“id”的节点时它会失败。我该如何解释?

//Parse XML
def page = new XmlSlurper(false,false).parseText(xml)

//Now save the value of the proper node to a property (this fails)
properties[ "finalValue" ] = page.find {
    it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};

我只需要考虑没有“id”属性的节点,这样它就不会失败。我该怎么做?

【问题讨论】:

    标签: grails groovy closures xmlslurper htmlcleaner


    【解决方案1】:

    您也可以使用 GPath 表示法,并先检查“@id”是否为空。

    下面的代码sn-p找到最后一个元素(由于id属性是“B”,值也是“bizz”,所以打印出“bizz”和“B”)。

    def xml = new XmlSlurper().parseText("<foo><bar>bizz</bar><bar id='A'>bazz</bar><bar id='B'>bizz</bar></foo>")
    def x =  xml.children().find{!it.@id.isEmpty() && it.text()=="bizz"}
    println x
    println x.@id
    

    【讨论】:

      【解决方案2】:

      显然,当我简单地使用 depthFirst 时,我可以让它工作。所以:

      properties[ "finalValue" ] = page.depthFirst().find {
          it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
      };
      

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-06
        • 2016-07-26
        相关资源
        最近更新 更多