GetFragment.xsl

Summary
Input of the transformation script is the XML document of which a fragment should be extracted. Parameters of the transformation script are: It returns an xml fragment between two milestone elements. The result sequence is wrapped into a parent element node.
 * ms1Name (first milestone name: e.g. "pb")
 * ms1Position (first milestone position: e.g. 5)
 * ms2Name (second milestone name: e.g. "pb")
 * ms2Position (second milestone position: e.g. 6)

Restrictions

 * uses the Saxon extension function "saxon:evaluate" (so the Saxon library is needed for this)
 * takes no care about namespaces
 * wrapping into parent node cannot be configured

Code




    



   

<xsl:variable name="ms1XPath" select="concat('subsequence(//*:', $ms1Name, ', ', $ms1Position, ', 1)')"/> <xsl:variable name="ms2XPath" select="concat('subsequence(//*:', $ms2Name, ', ', $ms2Position, ', 1)')"/> <xsl:variable name="ms1" select="saxon:evaluate($ms1XPath)" xmlns:saxon="http://saxon.sf.net/"/> <xsl:variable name="ms2" select="saxon:evaluate($ms2XPath)" xmlns:saxon="http://saxon.sf.net/"/> <xsl:variable name="ms1Ancestors" select="$ms1/ancestor::*"/> <xsl:variable name="ms2Ancestors" select="$ms2/ancestor::*"/>

<xsl:template match="element[local-name != $ms1Name and local-name != $ms2Name]"> <xsl:choose> <xsl:when test="(. >> $ms1 or fn:contains($ms1Ancestors, .)) and ($ms2 >> . or fn:contains($ms2Ancestors, .))"> <xsl:element name="{local-name(.)}"><xsl:apply-templates/></xsl:element> </xsl:when> <xsl:otherwise><xsl:apply-templates/></xsl:otherwise> </xsl:choose> </xsl:template>

<xsl:template match="attribute|text|comment|processing-instruction"> <xsl:choose> <xsl:when test=". >> $ms1 and $ms2 >> ."> <xsl:copy><xsl:apply-templates/></xsl:copy> </xsl:when> <xsl:otherwise><xsl:apply-templates/></xsl:otherwise> </xsl:choose> </xsl:template>

<xsl:template match="element[local-name = $ms1Name or local-name = $ms2Name]"> <xsl:choose> <xsl:when test=". is $ms1"> <xsl:element name="{local-name(.)}"><xsl:copy-of select="@*"></xsl:copy-of></xsl:element> </xsl:when> <xsl:when test=". is $ms2"> <xsl:element name="{local-name(.)}"><xsl:copy-of select="@*"></xsl:copy-of></xsl:element> </xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:template>

</xsl:stylesheet>