XSLT - 数字验证

时间:2015-10-07 08:52:29

标签: xml xslt xslt-2.0

我正在使用xslt对xml进行html转换,输入html我有这样的表,

<doc>
    <table>
        <tbody>
            <tr>
                <td rowspan="3">aaa</td>
                <td colspan="5">bbb</td>
                <td rowspan="3">ccc</td>
                <td colspan="2">ddd</td>
            </tr>
        </tbody>
    </table>
</doc>

使用xslt我需要生成以下输出,

<doc>
    <table>
        <tbody>
            <tr>
                <entry namest="1" morerows="2">aaa</entry>
                <entry namest="2" nameend="6">bbb</entry>
                <entry namest="7" morerows="2">ccc</entry>
                <entry namest="8" nameend="9">ddd</entry>
            </tr>
        </tbody>
    </table>
</doc>

为了完成这项任务,我写了以下xsl

<xsl:template match="td">

        <xsl:variable name="pre_rowspan" select="count(preceding-sibling::td[@rowspan])+1"/>
        <xsl:variable name="pre_colspan" select="preceding-sibling::td[@colspan]/@colspan"/>
        <xsl:variable name="numberof_pre_rowspan" select="count(preceding-sibling::td[@rowspan])+1"/>

        <entry>
            <xsl:attribute name="namest" select="number($pre_rowspan + $pre_colspan)"/>
            <xsl:if test="@rowspan">
                <xsl:attribute name="morerows" select="number(@rowspan)-1"/>
            </xsl:if>
            <xsl:if test="@colspan">
                <xsl:attribute name="nameend"
                    select="number(@colspan)+count(preceding-sibling::td[@rowspan])+number(preceding-sibling::td[@colspan]/@colspan)"
                />
            </xsl:if>

            <xsl:apply-templates/>
        </entry>
    </xsl:template>

这给了我正确的输出结构,但问题是当某些数字值为空时,它会显示属性的NaN

我的输出如下,

<doc>
    <table>
        <tbody>
            <tr>
                <entry namest="NaN" morerows="2">aaa</entry>
                <entry namest="NaN" nameend="NaN">bbb</entry>
                <entry namest="7" morerows="2">ccc</entry>
                <entry namest="8" nameend="9">ddd</entry>
            </tr>
        </tbody>
    </table>
</doc>

我们如何在XSLT中处理这种数字验证并返回0而不是NaN并获得正确的输出数值?

1 个答案:

答案 0 :(得分:2)

我建议您使用decimal-format指定NaN掩码:

<xsl:decimal-format name = "myformat" NaN = "0"/>

<xsl:template match="td">
    ...
    <xsl:attribute name="namest" select="format-number(number($pre_rowspan + $pre_colspan), '#0', 'myformat')"/>
    ...
</xsl:template>