Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy iterate Nodes with XMLHolder

Tags:

xml

groovy

soapui

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

like image 397
john Avatar asked Sep 29 '11 12:09

john


People also ask

What is groovy XmlSlurper?

Groovy's internal XmlParser and XmlSlurper provide access to XML documents in a Groovy-friendly way that supports GPath expressions for working on the document. XmlParser provides an in-memory representation for in-place manipulation of nodes, whereas XmlSlurper is able to work in a more streamlike fashion.

What is GPathResult?

GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().

What is node in groovy script?

Represents an arbitrary tree node which can be used for structured metadata or any arbitrary XML-like tree. A node can have a name, a value and an optional Map of attributes.


1 Answers

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
        }
    }
}
like image 59
ataylor Avatar answered Oct 06 '22 23:10

ataylor