首页 文章

使用xsl时XSLT失败:选择测试xsl:for-each的结果

提问于
浏览
1

我有一个 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 以捕获每个元素?我认为这与目前的背景有关?

非常感谢 .

2 回答

  • 1

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

    <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 .

  • 1

    按照另一个答案中的建议更改为 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>
    

相关问题