user2109043
user2109043

Reputation: 77

Iterate through EACH xml node with groovy, printing each node

I have a simple XML file like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<Things>
<thing indexNum='1'>
  <a>123</a>
  <b>456</b>
  <c>789</c>
</thing>
<thing indexNum='2'>
  <a>123</a>
  <b>456</b>
  <c>789</c>
</thing>
</Things>

The issue I'm facing is that I cannot simply get at each node separately with this code—it is printing ALL of the things, and what I'm attempting to do is to collect each node into a map, then interrogate/transform some key/value pairs in the map and replace them.

Here's my code; any chance someone can set me in the right direction?

def counter = 0

Things.thing.each { tag ->
  counter++
  println "\n--------------------------------  $counter  ------------------------------------"

  Things.thing.children().each { tags ->
    println "$counter${tags.name()}: $tags"
    return counter
  }
  println "\n$counter things processed...\n"
}

Would it be easier to manipulate this inside of a map?

Upvotes: 8

Views: 34475

Answers (1)

Dave Newton
Dave Newton

Reputation: 160181

The reason you keep getting the inner nodes is because you incorrectly iterate over the outer list twice. The inner loop should iterate only over tag:

doc = new XmlSlurper().parse("things.xml")
doc.thing.each { thing ->
  println "thing index: ${thing.@indexNum}"
  thing.children().each { tag ->
    println "  ${tag.name()}: ${tag.text()}"
  }
}

Output:

thing index: 1
  a: 123
  b: 456
  c: 789
thing index: 2
  a: 123
  b: 456
  c: 789

Upvotes: 17

Related Questions