Create a gist now

Instantly share code, notes, and snippets.

Groovy XmlSlurper sample
#!/usr/bin/groovy
//------------------------------------------------------
// Groovy XmlSlurper sample
//
//------------------------------------------------------
def xml = """
<aaa>
<langs type='current' count='3' mainstream='true'>
<language flavor='static' version='1.5'>Java3</language>
<language flavor='dynamic' version='1.6.0'>Groovy3</language>
<language flavor='dynamic' version='1.9'>JavaScript3</language>
</langs>
<langs type='current' count='4' mainstream='true'>
<language flavor='static' version='1.5'>Java4</language>
<language flavor='dynamic' version='1.6.0'>Groovy4</language>
<language flavor='dynamic' version='1.9'>JavaScript4</language>
</langs>
</aaa>
"""
//------------------------------------------------------
println "-"*40
println "-----language flavor='static' all-----"
println "-"*40
//------------------------------------------------------
aaa = new XmlSlurper().parseText(xml)
aaa.langs.language.each
{
if (it.@flavor.text() == "static"){
println it
}
}
//------------------------------------------------------
println "-"*40
println "-----langs count='3' language all-----"
println "-"*40
//------------------------------------------------------
aaa = new XmlSlurper().parseText(xml)
aaa.langs.each
{
if (it.@count.text() == "3")
{
it.language.each
{
println it.text()
}
}
}
/*
----- output -----
hoge@brokendish:~/tool/groovy$ groovy xml2.groovy
----------------------------------------
-----language flavor='static' all-----
----------------------------------------
Java3
Java4
----------------------------------------
-----langs count='3' language all-----
----------------------------------------
Java3
Groovy3
JavaScript3
hoge@brokendish:~/tool/groovy$
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment