我想根据一个条件环境分配多个变量。我知道如何仅对一个变量执行此操作:
<xsl:variable name="foo">
<xsl:choose>
<xsl:when test="$someCondition">
<xsl:value-of select="3"/>
<xsl:when>
<xsl:otherwise>
<xsl:value-of select="4711"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
但是,如果我想根据相同条件$ someCondition分配两个变量,该怎么办?
我不想再次写相同的xsl:choose语句,因为在实际示例中它有些冗长且计算量很大。
有问题的环境是带有exslt扩展名的libxslt(xslt 1.0)。
编辑:我想要的是一种类似于的行为
if (condition) {
foo = 1;
bar = "Fred";
}
else if (...) {
foo = 12;
bar = "ASDD";
}
(... more else ifs...)
else {
foo = ...;
bar = "...";
}
最佳答案
您可以做的是让您的主变量返回一个元素列表;每个要设置的变量一个
<xsl:variable name="all">
<xsl:choose>
<xsl:when test="a = 1">
<a>
<xsl:value-of select="1"/>
</a>
<b>
<xsl:value-of select="2"/>
</b>
</xsl:when>
<xsl:otherwise>
<a>
<xsl:value-of select="3"/>
</a>
<b>
<xsl:value-of select="4"/>
</b>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
然后,使用exslt函数,可以将其转换为“节点集”,然后可以使用该“节点集”来设置您的各个变量
<xsl:variable name="a" select="exsl:node-set($all)/a"/>
<xsl:variable name="b" select="exsl:node-set($all)/b"/>
别忘了,您需要为XSLT中的exslt函数声明namepsace才能起作用。
关于XSLT:根据条件设置多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12318006/