views:

292

answers:

1

Given a nice, simple XML structure, XmlSlurper() can allow me to read values from it very easily.

def xml = "<html><head><title>groovy</title></head></html>"

def html = new XmlSlurper().parseText(xml)

println html.head.title

Is there a way to make this simple tree navigation possible for generic (type-based, etc) XML. Ideally, in the snippet of code below, I'd like to walk the values by their name attribute, but instead, I have to do all this searching:

def genxml = """
<doc>
    <lst name = "head">
        <str name = "title">groovy</str>
        <str name = "keywords">java xml</str>
    </lst>
</doc>"""

def doc = new XmlSlurper().parseText(genxml)
println doc.lst.find { it.@name == "head" }.str.find { it.@name == "title" }

Is there a way to walk this just as:

println doc.head.title
A: 

head and title are attributes.

there are some really subtle differences between slurper and parser: http://www.ibm.com/developerworks/java/library/j-pg05199/

you can do this:

println "${doc.lst.str[0]} ${doc.lst.str[0].@name}"
println doc.lst.str.each { 
    println "${it} ${it.@name}"
    }

but look at the output:

groovy title
groovy title
java xml keywords
groovyjava xml
Ray Tayek