2017-10-11 105 views
2

我有一個XML文件等如下:XSL:計數連續屬性

<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> 

這是用「PD」屬性項的基本上的有序列表(值= 0或1)。 我需要顯示的結果如下:

  1. 用Pd = 1的行的總數,
  2. 用Pd = 1(0,如果最新的Pd = 0)
  3. 最大數目最新連續的行的用PD =

連續行的意甲我設法得到1和2,但未能達到3

我1 & 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,預期的結果應該是:

歡迎提供針對問題3的解決方案的任何幫助(以及對提供的其他解決方案的改進)

+0

您可以使用XSLT 2.0和這樣'XSL :for-each-group select =「// Row」group-adjacent =「@ Pd」'? –

+0

不幸的是,只有XSLT 1.0 ...即使分組是一回事,在這些組中獲得最長的序列也不會那麼容易。 – Tang

回答

1

以下是XSLT 1.0中執行第3個操作的一種方法,但它不會令人愉快(特別是因爲XSLT 1.0沒有max命令)。首先定義像這樣的關鍵...

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

然後,爲了獲得最大的系列PD =連續行的,你可以做到這一點

<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> 
+0

你可以編輯你的問題來顯示一個示例輸入,它不起作用嗎?我在http://xsltransform.net/a9GixJ測試了你當前的輸入,並且按照預期測試了總共7個。感謝 –

+0

我剛測試過它。對於提供的系列(1100001111111000111) - > 7,輸出正常。但是,對於不同的數據集,結果是錯誤的:(1100001110111000111) - > 6(應該是3)。我沒有足夠的流暢的xpath語法來解釋爲什麼... – Tang

+0

我已經糾正了這個問題。它失敗了,因爲它也包含了0的最大長度。 –