Project

Profile

Help

Bug #4636 ยป test.xsl

Michael Kay, 2020-07-08 11:10

 
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:els="http://www.lefebvre-sarrut.eu/ns/els"
exclude-result-prefixes="#all"
version="3.0"
>
<xd:doc>
<xd:desc>
<xd:p>Wrap elements starting with specific names into a new element "wrapper" </xd:p>
</xd:desc>
<xd:param name="context">Parent of the elements to wrap</xd:param>
<xd:param name="starts.names">sequence of names to set starting elements</xd:param>
<xd:param name="wrapper">element wrapper</xd:param>
<xd:param name="keep-context">Say if the context should be kept or not in the result</xd:param>
<xd:return>context (or its content) with wrapped element</xd:return>
</xd:doc>
<xsl:function name="els:wrap-elements-starting-with-names" as="node()*">
<xsl:param name="context" as="element()"/>
<xsl:param name="starts.names" as="xs:string+"/>
<xsl:param name="wrapper" as="element()"/>
<xsl:param name="keep-context" as="xs:boolean"/>
<xsl:sequence select="els:wrap-elements-starting-with(
$context,
function($e as element()) as xs:boolean {name($e) = $starts.names},
$wrapper,
$keep-context)"/>
</xsl:function>
<xd:doc>
<xd:desc>
<xd:p>Wrap elements starting with specific names into a new element "wrapper" </xd:p>
</xd:desc>
<xd:param name="context">Parent of the elements to wrap</xd:param>
<xd:param name="starts.function">xpath function to set the starting group condition</xd:param>
<xd:param name="wrapper">element wrapper</xd:param>
<xd:param name="keep-context">Say if the context should be kept or not in the result</xd:param>
<xd:return>context (or its content) with wrapped element</xd:return>
</xd:doc>
<xsl:function name="els:wrap-elements-starting-with" as="element()*">
<xsl:param name="context" as="element()"/>
<xsl:param name="starts.function"/> <!--as="xs:string"-->
<xsl:param name="wrapper" as="element()"/>
<xsl:param name="keep-context" as="xs:boolean"/>
<xsl:variable name="content" as="item()*">
<xsl:for-each-group select="$context/node()" group-starting-with="*[$starts.function(.)]">
<xsl:variable name="cg" select="current-group()" as="node()*"/>
<xsl:for-each select="$wrapper">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="$cg"/>
</xsl:copy>
</xsl:for-each>
</xsl:for-each-group>
</xsl:variable>
<xsl:choose>
<xsl:when test="$keep-context">
<xsl:for-each select="$context">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:sequence select="$content"/>
</xsl:copy>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:sequence select="$content"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>
</xsl:stylesheet>
    (1-1/1)