循环遍历 xpath 每次在 xslt 2 中获得正确的迭代

Looping through an xpath getting the right iteration each time in xslt 2

我有一个条件,我需要至少循环一次,所以我有以下 xsl 代码。但是,这不起作用,因为它总是获得最后一次迭代值。我该如何调整它以便在每个循环中获得正确的迭代?

 <xsl:variable name='count0'>
    <xsl:choose>
    <xsl:when test='count($_BoolCheck/BoolCheck[1]/CheckBoolType) = 0'>
      <xsl:value-of select="1"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select='count($_BoolCheck/BoolCheck[1]/CheckBoolType)'/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>
<xsl:for-each select="1 to $count0">
  <xsl:variable name='_LoopVar_2_0' select='$_BoolCheck/BoolCheck[1]/CheckBoolType[position()=$count0]'/>
  <e>
    <xsl:attribute name="n">ValueIsTrue</xsl:attribute>
    <xsl:attribute name="m">f</xsl:attribute>
    <xsl:attribute name="d">f</xsl:attribute>
    <xsl:if test="(ctvf:isTrue($_LoopVar_2_0/CheckBoolType[1]))">
      <xsl:value-of select="&quot;Value True&quot;"/>
    </xsl:if>
  </e>
</xsl:for-each>

xml文件如下:

<BoolCheck>
<CheckBoolType>true</CheckBoolType>
<CheckBoolType>false</CheckBoolType>
<CheckBoolType>1</CheckBoolType>
<CheckBoolType>0</CheckBoolType>
<CheckBoolType>True</CheckBoolType>
<CheckBoolType>False</CheckBoolType>
<CheckBoolType>TRUE</CheckBoolType>
<CheckBoolType>FALSE</CheckBoolType>
</BoolCheck>

在这种情况下,我需要遍历 CheckBoolType 的每次迭代并生成相应数量的值。但是,在上面的示例中,如果没有 CheckBoolType 迭代,我仍然希望迭代至少进入一次 for-each 循环。我希望能更清楚地说明这一点。

第一个观察:您对 $count0 的声明可以替换为

<xsl:variable name="temp" select="count($_BoolCheck/BoolCheck[1]/CheckBoolType)"/>
<xsl:variable name="count0" select="if ($temp=0) then 1 else $temp"/>

(很抱歉,如果这看起来无关紧要,但我调试代码的第一步始终是简化它。这使得错误更容易找到)。

执行此操作时,您可以安全地将谓词 [position()=$count0] 替换为 [$count0],因为 $count0 现在是整数而不是文档节点。 (更好的是,在 xsl:variable 声明中使用 as='xs:integer' 将其声明为整数。)

但是等一下,$count0 是正在处理的元素数,所以 CheckBoolType[$count] 总是 select 最后一个。那肯定不是你想要的。

这给我们带来了您代码中的另一个错误。变量 $_LoopVar_2_0 的值是一个名为 CheckBoolType 的元素节点。表达式 $_LoopVar_2_0/CheckBoolType[1] 正在查找此元素的 children,该元素也被命名为 CheckBoolType。没有这样的 children,所以表达式 select 是一个空序列,所以布尔测试总是假的。

在这个阶段,我想向您展示一些正确的代码来实现您想要的输出。不幸的是,您没有向我们展示所需的输出。我无法从 (a) 您的错误代码和 (b) 您对您尝试实现的算法的散文描述中对要求进行逆向工程。