且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XSLT 定义一个变量并检查它是否存在

更新时间:2023-11-25 23:26:40

由于您使用的是 XSLT 1.0,您可以使用 string() 进行测试.

Since you're using XSLT 1.0, you could use string() to do the test.

这是一个示例样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:variable name="foo" select="bar"/>
        <results>
            <xsl:choose>
                <xsl:when test="string($foo)">
                    <foo>DEFINED</foo>
                </xsl:when>
                <xsl:otherwise>
                    <foo>NOT DEFINED</foo>
                </xsl:otherwise>
            </xsl:choose>           
        </results>
    </xsl:template>

</xsl:stylesheet>

请注意,空白已折叠,因此 </bar> 将返回 false.此外,string() 将在直接测试元素而不是变量时起作用.

Note that white-space is collapsed so <bar> </bar> will return false. Also, string() will work when testing an element directly instead of a variable.

以下是一些输入/输出示例:

Here's some input/output examples:

输入

<test>
    <bar/>
</test>

<test>
    <bar></bar>
</test>

<test>
    <bar>    </bar>
</test>

输出

<foo>NOT DEFINED</foo>

输入

<test>
    <bar>x</bar>
</test>

输出

<foo>DEFINED</foo>

如果您可以使用 XSLT 2.0,您可以将变量声明为 xs:string 并在测试中使用变量名称 (test="$foo").


If you could use XSLT 2.0, you could declare the variable as an xs:string and just use the variable name in the test (test="$foo").

示例:

<xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xs">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:variable name="foo" select="bar" as="xs:string"/>
        <results>
            <xsl:choose>
                <xsl:when test="$foo">
                    <foo>DEFINED</foo>
                </xsl:when>
                <xsl:otherwise>
                    <foo>NOT DEFINED</foo>
                </xsl:otherwise>
            </xsl:choose>           
        </results>
    </xsl:template>

</xsl:stylesheet>