XSLT2.0:如果父级是相同的,则将一个标记中的所有节点作为一个解决方案

时间:2015-02-23 16:18:40

标签: xml xslt-2.0

您好我想为以下示例编写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>

1 个答案:

答案 0 :(得分:1)

您应该可以使用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>