GPATH查询-返回比较子节点的父节点

时间:2019-12-17 00:37:04

标签: groovy gpath

我是这个新手。我正在寻找其tag id属性与“ 4”匹配的所有videoGame节点。

    def text = '''
<videoGames>
    <videoGame category="A">
        <id>3</id>
        <name>testName 3</name>
        <releaseDate>2001-03-10T00:00:00Z</releaseDate>
        <tags attr="true">
           <tag id="4">41</tag>
           <tag id="3">31</tag>
        </tags>
    </videoGame>
    <videoGame category="B">
        <id>3</id>
        <name>testName 3</name>
        <releaseDate>2001-03-10T00:00:00Z</releaseDate>
        <tags attr="true">
           <tag id="3">41</tag>
           <tag id="7">31</tag>
        </tags>
    </videoGame>
</videoGames>
'''
def videoGames = new XmlSlurper().parseText(text)

def games = videoGames.videoGame.'**'.find { 
    node -> node.name() == 'tag' && node.@id == '4'
}

println games

我能够打印子节点,但是我没有成功获取父节点。有指针吗?

1 个答案:

答案 0 :(得分:0)

以下代码:

import groovy.xml.*

def text = '''
<videoGames>
    <videoGame category="A">
        <id>3</id>
        <name>testName 3</name>
        <releaseDate>2001-03-10T00:00:00Z</releaseDate>
        <tags attr="true">
           <tag id="4">41</tag>
           <tag id="3">31</tag>
        </tags>
    </videoGame>
    <videoGame category="B">
        <id>3</id>
        <name>testName 3</name>
        <releaseDate>2001-03-10T00:00:00Z</releaseDate>
        <tags attr="true">
           <tag id="3">41</tag>
           <tag id="7">31</tag>
        </tags>
    </videoGame>
</videoGames>
'''
def videoGames = new XmlSlurper().parseText(text)

def games = videoGames.videoGame.findAll { g ->
  g.tags.tag.any { tag -> 
    tag.@id == '4'
  }
}

def xmlString = XmlUtil.serialize(games)
println(xmlString)

运行时将产生以下输出:

─➤ groovy solution.groovy
<?xml version="1.0" encoding="UTF-8"?>
<videoGame category="A">
  <id>3</id>
  <name>testName 3</name>
  <releaseDate>2001-03-10T00:00:00Z</releaseDate>
  <tags attr="true">
    <tag id="4">41</tag>
    <tag id="3">31</tag>
  </tags>
</videoGame>

(由我添加的输出中的xml声明后的换行符)。