2013-04-16 122 views
1

我正在尝试转换一个XML文档。首先,我定义一个全局变量:XSLT定义一个变量并检查它是否存在后

<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

变量'foo'的变量定义之后定义。唯一的问题是它是否包含文本节点。 –

+0

如果我问如何检查文本节点是否被定义的问题,它会更好吗? – randombits

+0

如果输入包含“”或“”,您希望发生什么? –

回答

5

由于您使用的是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> 
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>如果它的工作原理定义。

+0

您不必声明'fn'前缀,也不需要将它添加到'boolean()'中。 –

0

变量foo将包含XML节点杆(不仅其文本是巴的内容)您的XML包含巴。因此,“@indeterminately sequenced”的答案是正确的,您可以测试foo是否包含test="boolean($foo)"的xml节点(条)。但我宁愿“测试= “名称($ 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>