【问题标题】:Groovy find nodes using gpath with certian child count and expressionGroovy 使用具有特定子计数和表达式的 xpath 查找节点
【发布时间】:2016-08-09 10:02:25
【问题描述】:

假设我有一个 XML

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <level0 id="1" t="0">
      <level1 id="lev1id01" att1="2015-05-12" val="12" status="0"/>
      <level1 id="lev1id02" att1="2015-06-13" val="13" status="0"/>
      <level1 id="lev1id03" att1="2015-07-10" val="13" status="0"/>
    </level0>

    <level0 id="2" t="0">
        <level1 id="lev1id11" att1="2015-05-12" val="121" status="0"/>
        <level1 id="lev1id12" att1="2015-06-13" val="132" status="0"/>
        <level1 id="lev1id13" att1="2015-07-11" val="113" status="0"/>
    </level0>

    <level0 id="2" t="1">
        <level1 id="lev1id21" att1="2015-05-12" val="121" status="0"/>
        <level1 id="lev1id22" att1="2015-06-13" val="132" status="0"/>
        <level1 id="lev1id23" att1="2015-07-11" val="113" status="0"/>
        <level1 id="lev1id23" att1="2015-07-11" val="113" status="0"/>
    </level0>
</data>

我想获取所有level0 节点(使用GPath),它们是:

  1. 如果level0/@t="0" 则仅当所有level1 子节点具有@status="0" 时选择此节点(level0
  2. 如果 level0/@t!="0" 则仅当 last level1 子节点具有 @status="0" 时才选择此节点 (level0)。最后我说的是level1 节点,最大值为@att1(假设@att1 包含yyyy-mm-dd 格式的日期)。

对于 XPath,我会使用 max() 和 count() 之类的函数,但我不知道如何使用 GPath 来完成。

谢谢

【问题讨论】:

    标签: groovy xml-parsing xmlslurper gpath


    【解决方案1】:

    Groovy 在Iterable 上定义的max()count() 函数可以在GPath 表达式中使用,以代替它们的XPath 等效项。

    // This closure is for level0[t=0] elements.
    // It selects the level0 if the count of its level1[status=0] children is 0.
    def t0Select = { level0 -> 
        level0.level1.count { level1 -> level1.@status != '0' } == 0 
    }
    
    // This closure is for level1[t=1] elements.
    // It selects the level0 if its level1 element with the maximum date has a status of "0" 
    def t1Select = { level0 -> 
        level0.level1.max { level1 -> Date.parse('yyyy-MM-dd', level1.@att1.toString()) }?.@status == '0' 
    }
    
    // Parse the XML and delegate to the appropriate closure above as per the t attribute
    def selected = new XmlSlurper().parseText(xml).level0.findAll { level0 -> 
        level0.@t == '0' ? t0Select(level0) : t1Select(level0) 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多