Groovy XmlSlurper access attribute value in root node

12,404

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'
Share:
12,404
JamesE
Author by

JamesE

Updated on June 05, 2022

Comments

  • JamesE
    JamesE almost 2 years

    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