我该怎么做才能使这段代码有效?
<xsl:choose>
<xsl:when test='type = 6'>
<xsl:variable name='title' select='root/info/title' />
</xsl:when>
<xsl:when test='type = 7'>
<xsl:variable name='title' select='root/name' />
</xsl:when>
<xsl:otherwise>
<xsl:variable name='title'>unknown</xsl:variable>
</xsl:otherwise>
</xsl:choose>
<div class='title'>
<xsl:value-of select='$title'/>
</div>
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为当我这样做时<xsl:value-of select='$title'/>,$title超出了范围.我试图<xsl:variable name='title'/>在范围之外添加该行,但这也不起作用,因为当我调用时<xsl:variable name='title' select='root/info/title' />,我之前已经设置了这个变量.我该怎么解决这个问题?
car*_*nts 31
您可以在变量设置中移动选择,如下所示:
<xsl:variable name="title">
<xsl:choose>
<xsl:when test='type=6'>
<xsl:value-of select="root/info/title" />
</xsl:when>
...
</xsl:choose>
</xsl:variable>
<div class='title'>
<xsl:value-of select="$title" />
</div>
Run Code Online (Sandbox Code Playgroud)
Dim*_*hev 14
Run Code Online (Sandbox Code Playgroud)<xsl:choose> <xsl:when test='type = 6'> <xsl:variable name='title' select='root/info/title' /> </xsl:when> <xsl:when test='type = 7'> <xsl:variable name='title' select='root/name' /> </xsl:when> <xsl:otherwise> <xsl:variable name='title'>unknown</xsl:variable> </xsl:otherwise> </xsl:choose> <div class='title'> <xsl:value-of select='$title'/> </div>这不起作用
这是一个FAQ:
您正在定义几个变量,每个变量都被命名$title,每个变量都无用,因为它会立即超出范围.
XSLT 1.0中基于条件定义变量的正确方法是:
<xsl:variable name="vTitle">
<xsl:choose>
<xsl:when test='type = 6'>
<xsl:value-of select='root/info/title' />
</xsl:when>
<xsl:when test='type = 7'>
<xsl:value-of select='root/name' />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'unknown'"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
Run Code Online (Sandbox Code Playgroud)
定义同一变量的另一种方法:在这种特殊情况下,您希望变量具有字符串值.这可以用更紧凑的形式表达:
<xsl:variable name="vTitle2" select=
"concat(root/info/title[current()/type=6],
root/name[current()/type=7],
substring('unknown', 1 div (type > 7 or not(type > 5)))
)
"/>
Run Code Online (Sandbox Code Playgroud)
最后,在XSLT 2.0中,可以更方便地定义这样的变量:
<xsl:variable name="vTitle3" as="xs:string" select=
"if(type eq 6)
then root/info/title
else if(type eq 7)
then root/name
else 'unknown'
"/>
Run Code Online (Sandbox Code Playgroud)