Xml – Merge XML documents

xml

I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have document1:

<mapping>
    <key value="assigned">
        <a/>
    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>

and document2:

<mapping>
    <key value="identity">
        <a/>
        <b/>
    </key>
</mapping>

I want to merge the two like this:

<mapping>
    <key value="identity">
        <a/>
        <b/>
    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>

I prefer Java or XSLT-based solutions, ant will do fine, but if there's an easy way to do that in Rake, Ruby or Python please don't be shy 🙂

EDIT: actually I find I'd rather use an automated tool/script, even writing it by myself, because manually merging some 30 XML files is a bit unwieldy… 🙁

Best Solution

If you like XSLT, there's a nice merge script I've used before at: Oliver's XSLT page