5

i want to Iterate over Nodes of an XML-File with the XML-Holder.

def reader = groovyUtils.getXmlHolder(test1 );

let's say the XML looks like the following:

<xml>
   <node>
      <val1/>
      <val2/>
   </node1>
   <node>
      <val1/>
      <val2/>
   </node2>
</xml>

i want to read the values from the different nodes. (val1, val2). So i tried like that:

for( node in reader.getNodeValues( "//ns1:node" ))
{}

It really iterates over the nodes, but i don't know how the get access to the values inside them.

Thanks a lot for your help!

john

Dónal
  • 185,044
  • 174
  • 569
  • 824
john
  • 81
  • 2
  • 2
  • 5

1 Answers1

7

Instead of getNodeValues, you probably want to call getDomNodes instead. That will return you standard Java DOM nodes of class org.w3c.dom.Node. From there you can traverse the child nodes starting with getFirstChild and iterating with getNextSibling. Groovy's DOMCategory adds some convenient helper methods that make it much less painful.

For example:

use (groovy.xml.dom.DOMCategory) {
    for( node in reader.getDomNodes( "//ns1:node" )) {
        node.children().each { child ->
            println child
        }
    }
}
Joost
  • 3,169
  • 2
  • 22
  • 40
ataylor
  • 64,891
  • 24
  • 161
  • 189