XSL:计算连续属性

时间:2017-10-11 16:36:23

标签: xml xslt

我有一个XML文件,如下所示:

<Query>
<Rows>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="0"></Row>
    <Row Pd="0"></Row>
    <Row Pd="0"></Row>
    <Row Pd="0"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="0"></Row>
    <Row Pd="0"></Row>
    <Row Pd="0"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
    <Row Pd="1"></Row>
</Rows>
</Query>

这基本上是一个带有&#34; Pd&#34;的项目的有序列表。 attribute(value = 0或1)。 我需要显示以下结果:

  
      
  1. Pd = 1的总行数,
  2.   
  3. Pd = 1的最新连续行数(如果最新Pd = 0则为0)
  4.   
  5. 连续行的最大系列,Pd = 1
  6.   

我设法得到1.和2.但未能达到3。

我的解决方案1&amp; 2(XSLT 1.0):

<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
    <div> 
        <h1>total # of Pd1 : <xsl:value-of select="sum(//Row/@Pd)"/></h1>
        <h1># of consecutive Pd1: <xsl:apply-templates/> </h1>
    </div> 
</xsl:template>
<xsl:template match="//Row[not(following-sibling::Row[1]/@Pd=self::Row/@Pd)][1]"> 
    <xsl:value-of select="sum(self::Row[1]/@Pd|preceding-sibling::Row/@Pd)"/>
</xsl:template>
</xsl:stylesheet>

对于上面引用的xml,预期结果应为:

  
      
  1. 12
  2.   
  3. 2
  4.   
  5. 7
  6.   

欢迎任何有关问题3解决方案的帮助(以及对其他解决方案的改进)

1 个答案:

答案 0 :(得分:1)

这是XSLT 1.0中的第3种方法,虽然它不会令人愉快(特别是因为XSLT 1.0没有max命令)。首先像这样定义一个键...

<xsl:key name="rows" match="Row" use="count(preceding-sibling::Row[@Pd != current()/@Pd])" />

然后,要获得Pd = 1的最大系列连续行,您可以执行此操作

<h1>
    <xsl:text>Largest serie of consecutive rows with Pd=1: </xsl:text>
    <xsl:for-each select="//Row[@Pd='1']">
        <xsl:sort select="count(key('rows', count(preceding-sibling::Row[@Pd != current()/@Pd]))[@Pd='1'])" order="descending" />
        <xsl:if test="position() = 1">
            <xsl:value-of select="count(key('rows', count(preceding-sibling::Row[@Pd != current()/@Pd]))[@Pd='1'])" />
        </xsl:if>
    </xsl:for-each>
</h1>