我正在尝试转换XML文档。首先,我定义了一个全局变量:
<xsl:variable name="foo"><xsl:value-of select="bar"/></xsl:variable>
现在,我正在转换的XML有可能定义了<bar>some data</bar>
。也有可能没有定义。
一旦我在下面声明了全局变量,我正在尝试输出以下内容,如果它已定义:
<foo>DEFINED</foo>
如果没有定义:
<foo>NOT DEFINED</foo>
我正在使用<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
最好的解决方法是什么?
答案 0 :(得分:6)
由于您使用的是XSLT 1.0,因此可以使用string()
进行测试。
这是一个示例样式表:
<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> </bar>
将返回false。此外,string()
将在直接测试元素而不是变量时起作用。
以下是一些输入/输出示例:
<强>输入强>
<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"
)。
示例:
<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>
答案 1 :(得分:0)
我不确定这是否有效但是......
将xmlns:fn="http://www.w3.org/2005/xpath-functions"
添加到样式表。
<xsl:choose>
<xsl:when test="fn:boolean(foo)">
<foo>DEFINED</foo>
</xsl:when>
<xsl:otherwise>
<foo>NOT DEFINED</foo>
</xsl:otherwise>
</xsl:choose>
编辑:@JimGarrison如果有效,我们会将<bar/>
或<bar></bar>
视为已定义。
答案 2 :(得分:0)
变量foo将包含xml节点栏(不仅是条形内容的文本)xml包含栏。因此,“@indeterminately sequenced”的答案是正确的,您可以测试foo是否包含带test="boolean($foo)"
的xml节点(bar)。但我更喜欢'test ='name($ foo)“. Or test="name($foo) = 'bar'
导致:
<xsl:variable name ="foo" select="*/bar" />
<xsl:template match="/">
<results>
<xsl:choose>
<xsl:when test="name($foo)">
<foo>DEFINED</foo>
</xsl:when>
<xsl:otherwise>
<foo>NOT DEFINED</foo>
</xsl:otherwise>
</xsl:choose>
</results>
</xsl:template>