使用 xsl:select 从 xsl:for-each 测试结果时 XSLT 失败



我有一个xsl:for-each,它将许多不同的元素组合在一起,然后有条件地处理每个元素。例如:

<xsl:for-each select=".//del | .//sup | .//unc | .//gap">
<xsl:choose>
<xsl:when test="del"><xsl:text>Output foo del</xsl:text></xsl:when>
<xsl:when test="sup"><xsl:text>Output foo sup</xsl:text></xsl:when>
<xsl:when test="unc"><xsl:text>Output foo unc</xsl:text></xsl:when>
<xsl:when test="gap"><xsl:text>Output foo gap</xsl:text></xsl:when> 
<xsl:otherwise><xsl:text>For each works, but the tests do not!</xsl:text></xsl:otherwise>
</xsl:choose>
<xsl:for-each>

<xsl:for-each>工作正常,因为它输出了很多<otherwise> For each works, but the tests do not!不知何故,我误解了如何编写@test来捕获每个元素?我认为这与当前背景有关?

非常感谢。

我不确定你想要实现什么,但它不应该这样读吗?

<xsl:for-each select=".//del | .//sup | .//unc | .//gap">
<xsl:choose>
<xsl:when test="self::del"><xsl:text>Output foo del</xsl:text></xsl:when>
<xsl:when test="self::sup"><xsl:text>Output foo sup</xsl:text></xsl:when>
<xsl:when test="self::unc"><xsl:text>Output foo unc</xsl:text></xsl:when>
<xsl:when test="self::gap"><xsl:text>Output foo gap</xsl:text></xsl:when> 
<xsl:otherwise><xsl:text>For each works, but the tests do not!</xsl:text></xsl:otherwise>
</xsl:choose>
<xsl:for-each>

或者,您必须声明xmlns="http://www.w3.org/1999/XSL/Transform"例如在choose甚至for-each内。

按照另一个答案中的建议更改为test="self::del"可以解决问题,但在 XSLT 中执行此操作的惯用方法是使用模板规则:

<xsl:apply-templates select=".//*" mode="m"/>

然后

<xsl:template match="del" mode="m">Output foo del</xsl:template>
<xsl:template match="sup" mode="m">Output foo sup</xsl:template>
<xsl:template match="unc" mode="m">Output foo unc</xsl:template>
<xsl:template match="gap" mode="m">Output foo gap</xsl:template>
<xsl:template match="*" mode="m">Otherwise</xsl:template>

最新更新