Preface:
GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identified. In this sense, it has similar aims and scope as XPath does for XML. The two main places where you use GPath expressions is when dealing with nested POJOs or when dealing with XML.
As an example, you can specify a path to an object or element of interest:
For XML, you can also specify attributes, e.g.:
Example:
- 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()}"
- def characters = node.character
- println "node:" + node.children().size()
- println "characters:" + 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.text()
- assert answer == "cheese"
Accessing element as property
- def characters = node.character
- def gromit = node.character[1]
- println gromit['@name']
- println gromit.@name
- println gromit.likes[0].text()
- println node.text()
Explore the DOM use children() and parent()
- def characters = node.children()
- for (c in characters) {
- println c.@name
- }
- def gromit = node.character.find { it.@id == '2' }
* Groovy Doc - Processing XML
* [ In Action ] Dynamic object orientation - Using power features
沒有留言:
張貼留言