1

假设我有一个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"
  2. 如果则仅当最后一个子节点具有时才level0/@t!="0"选择此节点 ( level0 ) 。当我最后说的时候,我的意思是具有最大值的节点(假设包含格式的日期)。 level1@status="0"level1@att1@att1yyyy-mm-dd

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

谢谢

4

1 回答 1

2

Groovy 定义的max()andcount()函数Iterable可以在 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) 
}
于 2016-08-09T12:21:40.130 回答