如何在XSLT中使用条件语句

k

我想选择包含“抽象”或“主体”标签的内容,但是我使用下面的代码从XSLT的两个标签中获取内容。如果删除“ xsl:if”,则对输出没有影响。

<xsl:template match="document">
<xsl:for-each select="./child::node()">
  <xsl:choose>        
    <xsl:when test="name() = 'abstract'">
      <xsl:call-template name="abstract"/>
    </xsl:when>
    <xsl:otherwise>
    <xsl:if test="name() = 'body'">
        <xsl:call-template name="body"/>
    </xsl:if>
    </xsl:otherwise>
  </xsl:choose>
</xsl:for-each> 

我必须在上面的代码中进行哪些更改?

马修

将条件词移出for-each

<xsl:template match="document">
    <xsl:choose>
        <xsl:when test="abstract">
            <xsl:for-each select="abstract">
                <xsl:call-template name="abstract"/>
            </xsl:for-each>
        </xsl:when>
        <xsl:otherwise>
            <xsl:for-each select="body">
                <xsl:call-template name="body"/>
            </xsl:for-each>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

我们首先测试是否有任何抽象元素。如果是这样,我们遍历所有抽象元素并调用适当的模板。

否则,我们将遍历body元素并调用适当的模板。

您现有的xsl遍历所有节点,并为每个节点检查节点名称,然后应用适当的模板。测试适用于各个节点。没有检查文档内容。

此处的区别在于,我们首先测试文档中存在哪些节点,然后仅在我们感兴趣的节点上循环。

替代方法

假设名为abstract的模板仅处理抽象节点,而名为body的模板仅处理主体节点,则使用匹配模板代替命名模板更为常见,这将使我们避免for-each循环

<xsl:template match="document">
    <xsl:choose>
        <xsl:when test="abstract">
            <xsl:apply-templates select="abstract"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:apply-templates select="body"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="abstract">
    <!-- Process abstract node here -->
</xsl:template>

<xsl:template match="body">
    <!-- Process body node here -->
</xsl:template>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章