Groovy XmlSlurper访问根节点中的属性值

Jam*_*esE 10 xml groovy xml-parsing

我正在尝试使用Groovy和XmlSlurper完成访问作为根节点一部分的属性.我可以使用嵌套节点轻松完成此操作,但似乎无法访问根节点.

这是XML结构(简化):

<coverage lines-covered="2353" lines-valid="2943">
    <sources />
    <packages />
</coverage>
Run Code Online (Sandbox Code Playgroud)

我希望能够获得行覆盖和行有效的属性值.这是我正在尝试的代码:

def cobertura = new XmlSlurper().parse(xml)
def coverage = cobertura.coverage
def lines = cobertura.find { it.@lines-covered }
println lines
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

def cobertura = new XmlSlurper().parse("cobertura-coverage.xml")
def coverage = cobertura.coverage
println coverage.@lines-covered
Run Code Online (Sandbox Code Playgroud)

和:

def cobertura = new XmlSlurper().parse("cobertura-coverage.xml")
println cobertura.@lines-covered
Run Code Online (Sandbox Code Playgroud)

gra*_*hey 21

您需要将lines-covered部分放在引号中,因为它包含一个破折号:

def cobertura = new XmlSlurper().parse("cobertura-coverage.xml")
println cobertura.@'lines-covered'
Run Code Online (Sandbox Code Playgroud)