Groovy iterate nodes using XMLHolder

I want to iterate over the nodes of an XML file using an XML-Holder.

def reader = groovyUtils.getXmlHolder(test1 ); 

let's say the XML looks like this:

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

I want to read values โ€‹โ€‹from different nodes. (val1, val2). So I tried like this:

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

It really does iterate over the nodes, but I don't know how to access the values โ€‹โ€‹inside them.

Many thanks for your help!

John

+4
source share
1 answer

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

For instance:

 use (groovy.xml.dom.DOMCategory) { for( node in reader.getDomNodes( "//ns1:node" )) { node.children().each { child -> println child } } } 
+7
source

All Articles