条件语句的XSLT快捷方式

时间:2013-09-11 19:25:24

标签: xml xslt xpath

我在一个大样式表中有大量的这个,这使得样式表变得非常麻烦:

<xsl:when test="Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted">
               "attempted": <xsl:value-of select="number(Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted)" />,</xsl:when><xsl:otherwise>
               "attempted": 0,</xsl:otherwise></xsl:choose>

基本上我要做的就是直截了当。我试图从相应的XPath中获取number()。如果失败,通常使用NaN,因为该字段不存在或字段不包含适合number()的值,我将其设置为零。

无论如何要么在一行中执行此操作,要么以某种方式创建一个可重用的组件,我可以应用于大量其他XPath节点我正在运行此代码?在我的代码的很多部分中继续做整个选择/否则模式似乎是错误的。

2 个答案:

答案 0 :(得分:0)

你可以像这样使用xsl:call-template

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:call-template name="myTemplate">
            <xsl:with-param name="myTestField" select="Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted" />
        </xsl:call-template>
        <xsl:call-template name="myTemplate">
            <xsl:with-param name="myTestField" select="Field_Goal_Stats/Field_Goal_Total/FGTtl_AttemptedSecondField" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="myTemplate">
        <xsl:param name="myTestField" />

        <xsl:choose>
            <xsl:when test="$myTestField">
                "attempted": <xsl:value-of select="number($myTestField)" />,
            </xsl:when>
            <xsl:otherwise>
                "attempted": 0,
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:0)

在XSLT 2.0中,你可以这样做:

<xsl:value-of select="(Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted,0)[1]"/>

当值存在时,你得到它......当值不存在时,结果序列的第一个值是0

这在XSLT 1.0中不可用。

相关问题