我需要翻转两个节点的元素。最初,变量是用以下命令设置的:
<xsl:variable name="matchesLeft" select="$questionObject/descendant::simpleMatchSet[position()=1]/simpleAssociableChoice"/>
<xsl:variable name="matchesRight" select="$questionObject/descendant::simpleMatchSet[position()=2]/simpleAssociableChoice"/>
我现在想用以下代码翻转变量:
<xsl:variable name="matchesRight">
<xsl:choose>
<xsl:when test="$flippedQuestions='true'">
<xsl:value-of select="$questionObject/descendant::simpleMatchSet[position()=2]/simpleAssociableChoice"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$questionObject/descendant::simpleMatchSet[position()=1]/simpleAssociableChoice"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
但它只从第一个元素获取值,而不是从节点中的所有元素获取值。我怎样才能做到这一点?
问题是xsl:variable/@select为您提供了一个节点集,但xsl:value of将节点集转换为其字符串值。您需要节点集。在XSLT1.0中,带内容的xsl:variable将始终为您提供一个结果树片段;但是在select属性中,您只能使用XPath1.0,它没有条件表达式。
当然,最好的解决方案是使用XSLT2.0来解决所有这些问题。使用1.0的有效理由数量一直在减少。如果必须使用1.0,那么XPath 1.0中会有一些复杂的解决方法来解决缺少条件表达式的问题,比如Dimitre所示的表达式。
使用:
<xsl:variable name="matchesRight" select=
"$questionObject/descendant::simpleMatchSet
[1+($flippedQuestions='true')]
/simpleAssociableChoice"/>
解释:
在XPath中,每当将布尔值$someBVal
传递给数值运算符(如+
)时,都会使用number($someBVal)
将布尔值转换为数字(0或1)。
根据定义:
number(false()) = 0
和
number(true()) = 1
因此
1+($flippedQuestions='true')
如果flippedQuestions
的字符串值不是字符串"true"
则计算为1,如果flippedQuestions
的字符串值是字符串"true"
则相同的表达式计算为2。