XSLT2.0:如果父节点相同,则将所有节点都放在一个标签中的解决方案

XSLT2.0: solution to take all nodes in one tag if parent is same

您好,我想为以下示例编写 xslt 2.0 解决方案。

我想获取一个角色中的所有子元素,直到节点成为另一个角色本身

输入xml

<para>
<character>
 <formatting>format</formatting>
</character>
<character>
 <formatting>format1</formatting
<formatting>format2</formatting
</character>
this is a text node
<character>
 <formatting>format3</formatting>
</character>
<character>
 <formatting>format7</formatting>
<formatting>format8</formatting>
</character>
</para>

预期输出

<para>
<character>

    <formatting>format</formatting>
    <formatting>format1</formatting>
    <formatting>format2</formatting>

</character>
this is a text node
<character>
<formatting>format3</formatting>
 <formatting>format7</formatting
<formatting>format8</formatting
</character>
</para>

您应该能够使用 xsl:for-each-group 并根据名称将相邻的分组。

示例...

XML 输入

<para>
    <character>
        <formatting>format</formatting>
    </character>
    <character>
        <formatting>format1</formatting>
        <formatting>format2</formatting>
    </character>
    this is a text node
    <character>
        <formatting>format3</formatting>
    </character>
    <character>
        <formatting>format7</formatting>
        <formatting>format8</formatting>
    </character>
</para>

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="para">
        <xsl:copy>
            <xsl:for-each-group select="node()" group-adjacent="name()">
                <xsl:choose>
                    <xsl:when test="current-group()[1][self::character]">
                        <character>
                            <xsl:apply-templates select="current-group()/node()"/>                            
                        </character>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()"/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>            
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

XML输出

<para>
   <character>
      <formatting>format</formatting>
      <formatting>format1</formatting>
      <formatting>format2</formatting>
   </character>
    this is a text node
    <character>
      <formatting>format3</formatting>
      <formatting>format7</formatting>
      <formatting>format8</formatting>
   </character>
</para>