Search code examples
parsingantxmltask

Copy one value over to another with xmltask


Is it possible for an xml task to copy the value of one node into another node for each element in a list?

Source XML:

<a>
 <b>
   <c1>foo</c1>
   <c2></c2>
 </b>
 <b>
   <c1>bar</c1>
   <c2></c2>
 </b>
 ...
</a>

Destination XML:

<a>
 <b>
   <c1>foo</c1>
   <c2>foo</c2>
 </b>
 <b>
   <c1>bar</c1>
   <c2>bar</c2>
 </b>
 ...
</a>

I'm trying to accomplish the above in my ant task, but I con't seem to find a way to do it, here is what I am doing so far,

<target name="mergefile">       
    <!-- Read the source into a buffer -->
    <xmltask source="source.xml" clearBuffers="list"> 
        <copy path="/a" buffer="list" append="true"/> 
    </xmltask>

    <!-- Write them to the output -->
    <xmltask source="destination.xml" dest="destination.xml"
        outputter="simple">
        <!-- First clear all the old paths. -->
        <remove path="/a/b"/> 
    <!-- Then add the resolved ones. -->
        <paste path="/a" buffer="list"></paste>
            <!-- Copy the value over? -->
        <replace path="a/b/c2/text()" withText="No Idea"/>
    </xmltask>
</target>

Any idea of how to copy the value from one node to the next for all the elements in the list?


Solution

  • As, I guess, is usually the case, writing my own task was the only way I could see to do it.

    @Override
    public void execute() throws BuildException {
       //Read file line by line, regex test on each line, 
       //matches get written back twice.
    }
    

    Then calling it was,

    <copyregmatch file="myfile.xml" regex=".*replace.*" />