GPATH query - Return the parent node comparing the child nodes

371 Views Asked by At

I am new to this groovy. I am looking for all the videoGame nodes whose tag id attribute matches to "4".

    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

I am able to print the child node but I have not been successful to get the parent node. Any pointers?

1

There are 1 best solutions below

0
On

The following code:

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)

will produce the following output when run:

─➤ 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>

(newline after xml declaration in the output added by me).