Xml – Groovy iterate Nodes with XMLHolder

groovysoapuixml

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

Best Answer

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