|
||||||||||
|
||||||||||
GroovyUsing Groovy
Language GuideJSRGroovy FeaturesModulesExamplesUseful LinksIDE SupportSupportCommunityDevelopersTools we use
Feeds
|
GPath is a path expression language we've integrated into Groovy which is similar in aims and scope as XPath is to XML. ExampleThe 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" } } Outline1.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' } ReferencesGetting Groovy with XML by Jack Herrington. |
|||||||||
|