1

I am using gpath to parse xml. I want to pull the pass/fail values from the stat object. The problem I have had is that the objects are being grouped together. I cannot access them separately.

This is the data I am working with.

<robot>
<statistics>
  <total>
    <stat fail="28" pass="10">Critical Tests</stat>
    <stat fail="28" pass="10">All Tests</stat>
  </total>
</statistics>
</robot>

when checking what groovy sees in these objects

*printing (stats.size()) returns 1

printing (stats.stat['@pass]) returns 1010

to clarify stats is a gpath object at the level.

It appears to simply concatenate the two different "stats"

Thanks!

edit:

Here is the code i have right now.

def stats = robot.statistics.total
    println(stats.size())
    println(stats.stat['@pass'])
    for (int i = 0; i < stats.size(); i++) {
        println(stats[i].stat)
        if (stats[i].stat == "All Tests") {
            println('i am here')
            println(stats[i].stat['@pass'])
            int totalPass = stats[i].stat['@pass']
            int totalFail = stats[i].stat['@fail']
        }
    }
Drew Royster
  • 120
  • 12

2 Answers2

1

Consider the following example re: iterate over the stat nodes (and compute the totals):

def xml = """
<robot>
<statistics>
  <total>
    <stat fail="28" pass="10">Critical Tests</stat>
    <stat fail="28" pass="10">All Tests</stat>
  </total>
</statistics>
</robot>
"""

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

int totalPass = 0
int totalFail = 0

robot.statistics.total.stat.each { statNode -> 
    println "processing: " + statNode.text()
    totalPass += (statNode.@'pass'.text() as int)
    totalFail += (statNode.@'fail'.text() as int) 
} 

println "totalPass: " + totalPass
println "totalFail: " + totalFail
Michael Easter
  • 23,733
  • 7
  • 76
  • 107
1

Or you could do:

def xmlText = """
<robot>
<statistics>
  <total>
    <stat fail="28" pass="10">Critical Tests</stat>
    <stat fail="28" pass="10">All Tests</stat>
  </total>
</statistics>
</robot>
"""

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

def result = ['pass', 'fail'].collectEntries {
    [it, xml.statistics.total.stat.@"$it"*.text()*.asType(Integer).sum()]
}

assert result == [pass:20, fail:56]
tim_yates
  • 167,322
  • 27
  • 342
  • 338