<xsl:stylesheet 
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 version="1.0">
  <xsl:output encoding="utf-8" indent="yes"/>
  <xsl:key name="S" match="w" use="substring-before(@id,'.')"/>

<xsl:template match="w">
  <xsl:variable name="sid">
    <xsl:value-of select="substring-before(@id,'.')"/>
  </xsl:variable>
  <xsl:if test="generate-id(key('S',$sid)[1])=generate-id(.)">
    <s n="{$sid}">
      <xsl:apply-templates select="key('S',$sid)" mode="copy"/>
    </s>
  </xsl:if>
</xsl:template>

<xsl:template match="w" mode="copy">
  <w>
    <xsl:copy-of select="@pos"/>
    <xsl:apply-templates/>
  </w>
  </xsl:template>

  <xsl:template match="*|@*|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates select="*|@*|processing-instruction()|comment()|text()"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="text()">
    <xsl:value-of select="."/> <!-- could normalize() here -->
  </xsl:template>
  
</xsl:stylesheet>


