Groovy XmlSlurper access attribute value in root node

groovy, xml, xml-parsing

Solution

You need to put the `lines-covered` part in quotes since it contains a dash:

def cobertura = new XmlSlurper().parse("cobertura-coverage.xml")
println cobertura.@'lines-covered'

Problem

I'm trying to accomplish accessing the attributes that are part of the root node using Groovy and XmlSlurper. I can do this easily with nested nodes, but can't seem to access the root node. Here is the XML structure (simplified): ``` <coverage lines-covered="2353" lines-valid="2943"> <sources /> <packages /> </coverage> ``` I'd like to be able to get to the lines-covered and lines-valid attribute values. Here is the code I'm trying out: ``` def cobertura = new XmlSlurper().parse(xml) def coverage = cobertura.coverage def lines = cobertura.find { it.@lines-covered } println lines ``` I've also tried: ``` def cobertura = new XmlSlurper().parse("cobertura-coverage.xml") def coverage = cobertura.coverage println coverage.@lines-covered ``` And: ``` def cobertura = new XmlSlurper().parse("cobertura-coverage.xml") println cobertura.@lines-covered ```

Original source