Adding one or incrementing variable in xslt

十年热恋 提交于 2019-12-20 05:01:21

问题


I want to make a Counter value getting incremented based on a condition. But i was not able to increment a value or add 1 to a global variable. I was using the following code

<xsl:variable name="count">0</xsl:variable>
<xsl:variable name="incre">1</xsl:variable>    

<xsl:template match="/">
  <xsl:if test="$video1 != ''">
    <xsl:variable name="count" select="number($count)+number($incrementor)"/>
    <!-- display video1 -->
  </xsl:if>
  <xsl:if test="$video2 != ''">
    <xsl:variable name="count" select="number($count)+number($incrementor)"/>
    <!-- display video2 -->
  </xsl:if>
  <xsl:if test="$video3 != ''">
    <xsl:if test="$count<2">
      <xsl:variable name="count" select="number($count)+number($incrementor)"/>
      <!-- display video3 -->
    </xs:if>
  </xsl:if>
  <xsl:if test="$video4 != ''">
    <xsl:if test="$count<2">
      <xsl:variable name="count" select="number($count)+number($incrementor)"/>
      <!-- display video4 -->
    </xs:if>
  </xsl:if>
</template>

How to increment the value of count or add 1 to it. Thanks in advance.


回答1:


Your problem arises from thinking like a procedural programmer when trying to use a functional language. It's a bad mix; tools work a lot better when you work with them and not against them.

Don't try to walk through the document and increment variables to keep count of things. Describe what you want in declarative terms.

Here, you want the first two non-empty <video> elements in the document to display, and you want the others (all the empty <video> elements and the third and later non-empty <video> elements) to be passed over in silence. (I'm making this up, of course: since you don't show your XML, I don't actually know what you really want, in XML terms.)

So you want a template to suppress empty <video> elements:

<xsl:template match="video[not(node())]"/>

And you want a template to suppress any <video> element preceded in the document by two or more non-empty <video> elements:

<xsl:template 
  match="video[count(preceding::video
                     [* or normalized-space(.)]
                    ) 
               > 1]"/>

And you want a template to display the first two non-empty <video> elements:

<xsl:template 
  match="video[* or normalized-space(.)]
              [count(preceding::video
                     [* or normalized-space(.)]
                    ) 
               &lt; 2]">

  <xsl:message>Displaying video ... </xsl:message>
  <!--* ... whatever else is needed to display the video ... *-->

<xsl:template>


来源:https://stackoverflow.com/questions/16838796/adding-one-or-incrementing-variable-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!