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
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.
GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With