Merging Documents with Identical Schema

Problem

You have two or more identically structured documents and you would like to merge them into a single document.

Solution

If the content of the documents is distinct or you are not concerned about duplicates, then the solution is simple:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   
<xsl:output method="xml" indent="yes"/>
   
<xsl:param name="doc2"/> 
   
<xsl:template match="/*">
  <xsl:copy>
    <xsl:copy-of select="* | document($doc2)/*/*"/>
  </xsl:copy>
</xsl:template>
   
</xsl:stylesheet>

If duplicates exist among input documents but you want the output document to contain unique entries, you can use techniques discussed in Recipe 4.3 for removing duplicates. Consider the following two documents in Example 6-12 and Example 6-13.

Example 6-12. Document 1

<people which="MeAndMyFriends">
     <person firstname="Sal" lastname="Mangano" age="38" height="5.75"/>
     <person firstname="Mike" lastname="Palmieri" age="28" height="5.10"/>
     <person firstname="Vito" lastname="Palmieri" age="38" height="6.0"/>
     <person firstname="Vinny" lastname="Mari" age="37" height="5.8"/>
</people>

Example 6-13. Document 2

<people which="MeAndMyCoWorkers">
     <person firstname="Sal" lastname="Mangano" age="38" height="5.75"/>
     <person firstname="Al" lastname="Zehtooney" age="33" height="5.3"/>
     <person firstname="Brad" lastname="York" age="38" height="6.0"/>
     <person firstname="Charles" lastname="Xavier" age="32" height="5.8"/>
</people>

This stylesheet merges ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.