将值放在变量中并在XSLT中使用它

时间:2013-03-26 06:09:54

标签: xml xslt xslt-1.0

<xsl:choose>
  <xsl:when test="type='LEVEL'">
    <xsl:variable name="myVar" select = "value"/>
      <xsl:variable name="spaces" select = "'&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0'"/>
      <xsl:value-of select="substring($spaces, 1, $myVar)"/>
   </xsl:when>

我在XSLT中有上面的代码。 myVar是一个变量,其值为(1或2或3)。 我需要将以下代码行的输出存储在变量中,并在when条件之外使用它。

xsl:value-of select="substring($spaces, 1, $myVar)"/

我目前无法做到。 有人可以建议吗?

2 个答案:

答案 0 :(得分:0)

你做不到。 您可以在when条件之外声明变量(即使它们的声明中的某些XPath失败并返回null),或者使用when条件中的输出。 但是,如果你想使用输出,为什么还要选择? 最后一次尝试,可能是声明变量并在其序列构造函数中使用choose,如下所示:

<!-- You declare the 'tool' variables alone -->
<xsl:variable name="myVar" select = "value"/>
<xsl:variable name="spaces" select = "'&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0'"/>

<!-- For myVarSub you use a sequence constructor instead of the select way -->
<xsl:variable name="myVarSub">      
    <xsl:choose>
       <xsl:when test="type='LEVEL'">    
            <!-- xsl:sequence create xml node -->
            <xsl:sequence select="substring($spaces, 1, $myVar)"/>
       </xsl:when>
    <xsl:choose>
</xsl:variable>

之后,只需在需要时输出或使用变量。如果在条件时不添加其他,则当测试为false时,myVar将为null。但请注意,这是一个xslt 2.0解决方案,因为xsl:sequence。

答案 1 :(得分:0)

我不确定你要做什么,但你可以尝试以下方法。 源XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Result>
<resultDetails>
    <resultDetailsData>
        <itemProperties>
            <ID>1</ID>
            <type>LEVEL</type> 
            <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:int">5</value> 
        </itemProperties>
    </resultDetailsData>
</resultDetails>
</Result>

应用此XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">


<xsl:template match="itemProperties">
    <xsl:variable name="fromOutputTemplate">
        <xsl:call-template name="output"/>  
    </xsl:variable>
    <out>
        <xsl:value-of select="$fromOutputTemplate"/>    
    </out>          
</xsl:template>

<xsl:template name="output">
    <xsl:variable name="spaces" select = "'&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;'"/>
    <xsl:variable name="myVar" select = "value"/>

    <xsl:choose>
        <xsl:when test="type='LEVEL'">
                <xsl:value-of select="substring($spaces, 1, $myVar)"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>


</xsl:stylesheet>

它为您提供此输出:

<?xml version="1.0" encoding="UTF-8"?>


        <out>     </out>

这是你想去的方式吗?

祝你好运, 彼得