XSLT 定义一个变量并检查它是否存在 [英] XSLT define a variable and check if it exists after
问题描述
我正在尝试转换 XML 文档.首先,我定义了一个全局变量:
I am attempting to transform an XML document. First, I am defining a global variable:
<xsl:variable name="foo"><xsl:value-of select="bar"/></xsl:variable>
现在我正在转换的 XML 有可能定义了
.也有可能没有定义.
Now there is a chance that the XML I'm transforming has <bar>some data</bar>
defined. There is also a chance that it is not defined.
一旦我在下面声明了全局变量,如果定义了它,我将尝试输出以下内容:
Once I declare the global variable below, I'm trying to output the following if it is defined:
<foo>DEFINED</foo>
如果没有定义:
<foo>NOT DEFINED</foo>
我正在使用 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
解决这个问题的最佳方法是什么?
What's the best way of going about this?
推荐答案
由于您使用的是 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>
请注意,空白已折叠,因此
将返回 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>
这篇关于XSLT 定义一个变量并检查它是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!