XSLT-2.0:按节点内容分组

时间:2017-02-05 17:35:25

标签: xml xslt xslt-2.0

我们需要在第一列的内容上执行分组表行,然后对该组中的每一行执行一定量的处理。第一列的内容 - 数字。如果列不包含任意数量的数字,则将接近for-each-group

示例输入:



<table>
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
  <tr><td>1</td></tr>
  <tr><td>1,2,3</td></tr>
  <tr><td>1,4</td></tr>
</table>
&#13;
&#13;
&#13;

根据任务,我应该有4组:

  • 列中的数字1:1,3,4,5行;
  • 第2栏和第4栏中的数字2;
  • 3号:4号;
  • 4:5th。

通用模板如下所示:

&#13;
&#13;
<xsl:template match="table">
  <xsl:for-each-group select="tr" group-by="td[1]"> 
   <xsl:for-each select="current-group()">  
    <!-- transformation -->
   </xsl:for-each>
  </xsl:for-each-group>
</xsl:template>
&#13;
&#13;
&#13;

group-by = "td [1]"无法正常工作 正则表达式的关键......我觉得很困难。

3 个答案:

答案 0 :(得分:2)

听起来好像要将<xsl:for-each-group select="tr" group-by="tokenize(td[1], ',')">替换为{{1}}。

答案 1 :(得分:0)

我想你是在说那个

  1. 作为输入,您有一个包含行和列的表。
  2. 每行的第一列包含以逗号分隔的数字列表。行可能包含其他列,但这些列未在您的示例中显示。
  3. 作为输出,您需要为逗号分隔的数字列表中的每个不同数值创建一个组,其中包含在第一列中以逗号分隔的列表中包含该数字值的行。
  4. 从最后一点开始,对于第一列中逗号分隔列表中的每个数字,一行将出现一次,或者对于该列表中的每个不同值出现一次(规范不清楚)。

    我试试

    <xsl:for-each-group select="tr"
      group-by="tokenize(td[1],',')">
      <xsl:message>Now processing <xsl:value-of 
          select="count(current-group()"/>rows containing <xsl:value-of 
          select="current-grouping-key()"/> in column 1.</
      ...
    </
    

    (未经测试。)

答案 2 :(得分:0)

如果要输出包含每个组值的原始行号,我认为您需要将输入转换为另一个包含原始position()的数据结构。像这样:

<xsl:template match="table">
    <xsl:variable name="row-data">
        <xsl:for-each select="tr/td">
            <xsl:variable name="row" select="position()" />
            <xsl:for-each select="tokenize(., ',')">
                <data>
                <xsl:attribute name="row" select="$row" />
                <xsl:attribute name="value" select="." />
                </data>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:variable>

    <data>
      <xsl:for-each-group select="$row-data/*" group-by="@value"> 
       <group>
            <xsl:attribute name="value" select="@value" />
            <xsl:value-of select="current-group()/@row" separator=","/>
       </group>
      </xsl:for-each-group>
    </data>
</xsl:template>