Groovy

Using Groovy

Language Guide

JSR

Groovy Features

Modules

Examples

Useful Links

IDE Support

Support

Community

Developers

Tools we use

IntelliJ IDEA
YourKit profiler

Feeds


Site
News
GPath

GPath is a path expression language we've integrated into Groovy which is similar in aims and scope as XPath is to XML.
1. Expression language for tree structured data
2. Implementations for XML
3. Can specify a path to an element
a.b.c -> all the <c> elements inside <b> inside <a>
4. Can specify attributes
a["@href"] -> the href attribute of all the a elements

Example

The best example of GPath for xml is test-new/groovy/util/XmlSlurperTest.groovy.

package org.codehaus.groovy.sandbox.util

class XmlSlurperTest extends GroovyTestCase {
    
void testXmlParser() {
    def text = """
<characters>
  <props>
    <prop>dd</prop>
  </props>
  <character id="1" name="Wallace">
     <likes>cheese</likes>
  </character>
  <character id="2" name="Gromit">
    <likes>sleep</likes>
  </character>
</characters>
"""
        
    def node = new XmlSlurper().parseText(text);
        
    assert node != null
    assert node.children().size() == 3 //, "Children ${node.children()}"
        
    characters = node.character
    println "node:" + node.children().size()
    println "charcters:" + node.character.size()
    for (c in characters) {
        println c['@name']
    }
        
    assert characters.size() == 2
        
    assert node.character.likes.size() == 2 //, "Likes ${node.character.likes}"
        
    // lets find Gromit
    def gromit = node.character.find { it['@id'] == '2' }
    assert gromit != null //, "Should have found Gromit!"
    assert gromit['@name'] == "Gromit"        
        
    // lets find what Wallace likes in 1 query
    def answer = node.character.find { it['@id'] == '1' }.likes[0].text()
    assert answer == "cheese"
}
}

Outline

1.Accessing element as property

def  characters = node.character 
def  gromit =  node.character[1]

2.Accessing attributes

println gromit['@name']

3.Accessing element body

println gromit.likes[0].text()
println node.text()

If the element is a father node,it will print all children's text.

3.Explore the DOM use children() and parent()

def characters = node.children()
for (c in characters) {
    println c['@name']
}

but the parent() is not implement in current version XmlSlurper.java, i had upload an attachement to patch it.

4.Find elements use expression

def gromit = node.character.find { it['@id'] == '2' }

References

Getting Groovy with XML by Jack Herrington.
See some examples.