在xsl中具有相同名称的多个块中的每个块的排序和分组

时间:2014-01-17 20:30:34

标签: xml sorting xslt

XML结构:

<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="c">
           <Rate>0.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="a">
           <Rate>1.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="b">
           <Rate>0.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>
<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="c">
           <Rate>0.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>
<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="e">
           <Rate>2.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="f">
           <Rate>0.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>

我需要将每个AvailableList分组为&#34; Rate&#34;然后按属性&#34; Name&#34;。

排序

Modified XML结构应该是:

<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="b">
           <Rate>0.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="c">
           <Rate>0.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="a">
           <Rate>1.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>
<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="c">
           <Rate>0.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>
<AvailableList>
    <TimePeriod>
       <DetailPeriod Name="e">
           <Rate>2.0</Rate>
       </DetailPeriod>
       <DetailPeriod Name="f">
           <Rate>0.0</Rate>
       </DetailPeriod>
    </TimePeriod>
</AvailableList>

我有以下xslt代码:

xsl:key name =&#34; RatesKey&#34;匹配=&#34; DetailPeriod&#34;使用=&#34;速率&#34 /

    <xsl:for-each select="DetailPeriod[generate-id(.) =  generate-id(key('RatesKey', Rate)[1])]">
      <xsl:sort select="@Name"/>
        <xsl:for-each select="key('RatesKey', Rate)">
          <xsl:variable name="varCount" select="count(key('RatesKey', Rate))"/>                      
        </xsl:for-each>
    </xsl:for-each>

我仍在尝试分组和排序。当我为第一个TimePeriod打印$ varCount的值时,我希望当Rate = 0.0时看到varCount = 2,但我看到varCount = 4。它正在考虑所有TimePeriod块。如何根据TimePeriod块将代码更改为分组和排序?

1 个答案:

答案 0 :(得分:0)

你实际上并不需要任何分组来实现你在问题中给出的所需输出,只是按比率在数字上进行两级排序,然后按名称按字母顺序排列

<xsl:for-each select="DetailPeriod">
  <xsl:sort select="Rate" data-type="number" />
  <xsl:sort select="@Name" />

但一般来说,当您想要将Muenchian分组限制为在特定父元素中分组时,您需要将该元素的唯一内容包含在键值的一部分中,例如

<xsl:key name="RatesKey" match="DetailPeriod"
  use="concat(generate-id(ancestor::AvailableList[1]), '|', Rate)" />

<xsl:for-each select="DetailPeriod[generate-id() = generate-id(
  key('RatesKey', concat(generate-id(current()/..), '|', Rate))[1])]">