Assert XML block from a text file with Groovy

58 views Asked by At

I have an xml file that contains couple of blocks that have the same parent name, but contain different tags with different values:

<Block>
   <tag1>123</tag1>
   <tag2>456</tag2>
   <tag3>789</tag3>
</Block>
<Block>
   <tag1>321</tag1>
   <tag2>654</tag2>
   <tag3>987</tag3>
</Block>
<Block>
   <tag1>111</tag1>
   <tag2>444</tag2>
   <tag3>777</tag3>
</Block>
<Block>
   <tag1>22</tag1>
   <tag2>55</tag2>
   <tag3>88</tag3>
</Block>

This file is generated after a specific request based on some inputs and each time should contain specific values.

I want to create a groovy script that automatically verifies the values in the tags of each individual block, but since all these blocks have the same name and I am relatively new at this I can't manage to do it :( Can you help me with with that?

1

There are 1 answers

4
Matouš Klugar On BEST ANSWER

The basic working with XML might look like this

File inputFile = new File("path")
def xml = new XmlParser(false, false).parse(inputFile)

xml.Block.each{
    int sum = 0
    sum += it.tag1.toInt()
    sum += it.tag2.toInt()
    sum += it.tag3.toInt()
}

You can validate it based on the sum or whatever you need