声明一个xsl变量并为其赋值 [英] Declaring a xsl variable and assigning value to it
问题描述
我正在开发一个使用apache茧将XML转换为PDF的应用程序,并且我正在重新设计处理输入XML的XSL.
I'm working on an application which uses apache cocoon to convert an XML to PDF, and I'm redesigning the XSL that handles the input XML.
当前在XSL中,我们有这样的代码
Currently in the XSL, we have code like this
<xsl:variable name="variable1">
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'A'"/>
</xsl:when>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'B'"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:variable name="variable2">
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'X'"/>
</xsl:when>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'Y'"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
如果将其更改为此可以使用吗?
Will it work if I change it to this?
<xsl:variable name="variable1"/>
<xsl:variable name="variable2"/>
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:variable name="variable1" select="'A'">
<xsl:variable name="variable2" select="'X'">
</xsl:when>
<xsl:when test="$testVariable ='2'">
<xsl:variable name="variable1" select="'B'">
<xsl:variable name="variable2" select="'Y'">
</xsl:when>
</xsl:choose>
推荐答案
否,与许多其他语言不同,XSLT变量在创建后无法更改其值.但是,您可以使用以下技术来避免多余的代码:
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
实际上,一旦获得了values
变量,您甚至可能不需要单独的variable1
和variable2
变量.您可以只使用$values/@v1
和$values/@v2
.
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
这篇关于声明一个xsl变量并为其赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!