Ant Script to Copy a Snippet of a XML to Another XML
I know, Ant is not the most modern technology, but there are still Ant-based systems we have to maintenance.
Sometimes we need to cut or copy a piece of a XML document and save it to another.
We will use XmlTask library by OOPS Consultancy to achive this goal.
First of all, we have to define an Ant task:
<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" />
Don't forget to put the downloaded library into the Ant libs folder or onto the classpath:
ant ... -lib xmltask.jar
Let's consider two XML configuration files:
conf.xml
<configuration> <applications> <app id="MyCoolApp" /> <app id="AnotherApp" /> </applications> </configuration>
settings.xml
<settings> ... <apps> <app id="thisAppWasAlreadyHere" /> </apps> </settings>
And we want to merge those documents in the way we get this content of the settings.xml
:
<settings> ... <apps> <app id="thisAppWasAlreadyHere" /> <app id="MyCoolApp" /> <app id="AnotherApp" /> </apps> </settings>
We can use the xmltask's command call to get a path-defined snippet into the buffer and append it with the command insert.
Here is the whole code:
<xmltask source="conf.xml"> <call path="configuration/applications/app" buffer="apps_storedXml"> <param name="id" path="@id" /> <actions> <echo>Merge the app id="@{id}"</echo> <xmltask source="settings.xml" dest="settings.xml"> <insert path="settings/apps" buffer="apps_storedXml" /> </xmltask> </actions> </call> </xmltask>
That's it!