xmlparsinggroovygpath

gpath accessing data from objects with identical names


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']
        }
    }

Solution

  • 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