<xsl:template match="/">
<xsl:for-each select="*[1]"> <!--this is for the root only-->
<xsl:copy> <!-- copy root node and his attributes -->
<xsl:copy-of select="@*"/>
<!--
- group the B elements by attribute "id"
- eliminate duplicates
- sort by attribute "id"
-->
<xsl:for-each select="*[generate-id() = generate-id(key('id', @id)[1])]">
<xsl:sort select="@id"/>
<!-- copy children nodes C using the attribute id as key -->
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="key('children', @id)"/>
</xsl:copy>