使用for-each-groups的嵌套分组

时间:2011-02-17 10:11:53

标签: xslt xslt-2.0

我有以下示例嵌套XML

<?xml version="1.0" encoding="UTF-8"?>
<text>
    <main>
        <div n="Section 1">
            <milestone unit="fragment"/>

            <div rend="header">
                <head>One</head>
            </div>
        </div>

        <div n="Section 2">
             <milestone unit="fragment"/>

              <div rend="header">
                <head>Two</head>
               </div>

            <div>
                <p>Para 1</p>
                <p>Para 2</p>
                <p>Para 3</p>

                <milestone unit="fragment"/>

                <p>Para 4</p>
                <p>Para 5</p>
                <p>Para 6</p>

                <milestone unit="fragment"/>

                <p>Para 7</p>
                <p>Para 8</p>
                <p>Para 9</p>

            </div>
        </div>
    </main>
</text>

我试图把它分成这样的片段:

 <div n="1">
         One
    </div>

    <div n="2">
         Two

         Para 1
         Para 2
         Para 3

    </div> 

    <div n="3">
         Para 4
         Para 5
         Para 6
    </div>

    <div n="4">
        Para 7
        Para 8
        Para 9
    </div>

这是我正在使用的XSLT

<xsl:template match="/">
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="text">
    <xsl:for-each select="main/div">
        <xsl:for-each-group select="*" group-starting-with="milestone[@unit='fragment']">
            <xsl:for-each select="current-group()" >
                <xsl:variable name="fragNum"><xsl:number count="milestone[@unit='fragment']" level="any" from="body"/></xsl:variable>
                <div n="{$fragNum}">
                    <xsl:apply-templates select="."/>    
                </div>
            </xsl:for-each>
        </xsl:for-each-group>
    </xsl:for-each>
</xsl:template>

这是转换的输出:

  <div n=""/>
        <div n="">
            One
        </div>
        <div n=""/>
    <div n="">
        Two
    </div>
    <div n="">
        Para 1
        Para 2
        Para 3



        Para 4
        Para 5
        Para 6



        Para 7
        Para 8
        Para 9
    </div>

即使我告诉每个组,分组应该从“里程碑[@ unit ='fragment']开始,为什么当里程碑标记嵌套在div中时忽略它?

2 个答案:

答案 0 :(得分:2)

样式表为

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

  <xsl:output indent="yes"/>

  <xsl:template match="text">
    <xsl:for-each-group select="descendant::*[not(*)]"
      group-starting-with="milestone[@unit = 'fragment']">
      <div n="{position()}">
        <xsl:value-of select="current-group()" separator="&#10;"/>
      </div>
    </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

Saxon 9输出

<div n="1">
One</div>
<div n="2">
Two
Para 1
Para 2
Para 3</div>
<div n="3">
Para 4
Para 5
Para 6</div>
<div n="4">
Para 7
Para 8
Para 9</div>

答案 1 :(得分:0)

您似乎只在main/div中选择for-each-group的子元素。因此,(从for-each-groups元素的角度来看)没有milestone元素嵌套在div的下一层中。