Find GPath exists in given XML document using Groovy

396 Views Asked by At

In Groovy given a GPath I want to find that the path exists in XML document. So that I can set a value for the node. I can use xmlslurper for parsing the document. GPath is a string path represented in slashes format.

1

There are 1 best solutions below

0
On

Look at example:

def xml = '''
    <?xml version="1.0" encoding="UTF-8"?>
    <data>
      <level0 id="1" t="0">
      <level1 id="lev1id01" att1="2015-05-12" val="12" status="0" year="2015" month="05" />
    </level0>
    </data>
'''

// find all nodes named 'level1'
def level1Nodes = new XmlSlurper().parseText(xml).level0.level1

// display found nodes names
level1Nodes.each { node ->
    println "node: ${node.name()}"
}

// Get 'year' attribute value for 'level1' node
def level1YearValue = level1Nodes.each { node ->
    println "${node.@year}"
}

Could you be more specific in your question?