I have an input like this:
<root>
<results>
<loc>Loc 10</loc>
<loc_name>Loc Desc10</loc_name>
<points>3</points>
<StartDate>2023-09-11T22:39:40Z</StartDate>
<EndDate>2023-09-13T22:45:36.437000Z</EndDate>
</results>
<results>
<loc>Loc 11</loc>
<loc_name>Loc Desc 11</loc_name>
<points>4</points>
<StartDate>2023-09-16T22:39:40Z</StartDate>
<EndDate>2023-09-18T22:45:36.437000Z</EndDate>
</results>
</root>
I want to duplicate the data for every day between start and end date. Want to have an output like:
<root>
<results>
<loc>Loc 10</loc>
<loc_name>Loc Desc10</loc_name>
<points>3</points>
<Date>2023-09-11T22:39:40Z</Date>
</results>
<results>
<loc>Loc 10</loc>
<loc_name>Loc Desc10</loc_name>
<points>3</points>
<Date>2023-09-12T22:39:40Z</Date>
</results>
<results>
<loc>Loc 10</loc>
<loc_name>Loc Desc10</loc_name>
<points>3</points>
<Date>2023-09-13T22:39:40Z</Date>
</results>
<results>
<loc>Loc 11</loc>
<loc_name>Loc Desc11</loc_name>
<point>4</points>
<Date>2023-09-16T22:39:40Z</Date>
</results>
<results>
<loc>Loc 11</loc>
<loc_name>Loc Desc11</loc_name>
<point>4</points>
<Date>2023-09-17T22:39:40Z</Date>
</results>
<results>
<loc>Loc 11</loc>
<loc_name>Loc Desc11</loc_name>
<point>4</points>
<Date>2023-09-18T22:39:40Z</Date>
</results>
</root>
How can we do this in groovy?
I am unable to find any examples on how to loop over the payload and create this new payload in Groovy
Here is a quick script that does what you are looking for:
A few things I noticed and should explain. The
StartDatenode andEndDatenodes have different date formats. Seems strange. You might want to clean that up if you control the generation of this XML.The trick is that
parseTextreturns aGPathResultwhich allows you to execute queries across the xml nodes (iexml.results.eachto iterate over the nodes under the root element). You also have access to the groovy collection methods (iefindAll,collect,each, etc). So the loop used to copy the nodes from the input document into the output usesfindAllto filter it all nodes that aren'tStartDateorEndDatethe iterates that set usingeach.