Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml 声明xsl变量并为其赋值_Xml_Xslt_Xpath_Apache Cocoon - Fatal编程技术网

Xml 声明xsl变量并为其赋值

Xml 声明xsl变量并为其赋值,xml,xslt,xpath,apache-cocoon,Xml,Xslt,Xpath,Apache Cocoon,我正在开发一个应用程序,它使用ApacheCook将XML转换为PDF,我正在重新设计处理输入XML的XSL 目前在XSL中,我们有这样的代码 <xsl:variable name="variable1"> <xsl:choose> <xsl:when test="$testVariable ='1'"> <xsl:value-of select="'A'"/> </xsl:when>

我正在开发一个应用程序,它使用ApacheCook将XML转换为PDF,我正在重新设计处理输入XML的XSL

目前在XSL中,我们有这样的代码

<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>

如果我把它改成这个能用吗

<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变量在创建后不能更改其值。但是,您可以使用以下技术避免无关代码:

<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>


事实上,一旦获得了
变量,您甚至可能不需要单独的
变量1
变量2
变量。您只需使用
$values/@v1
$values/@v2
即可。

谢谢您。我在上面写的例子是对存在的东西的简单表示。实际上,有很多变量和嵌套。我正在寻找一种优化的方法it@RaviShenoy我不确定这是否意味着我充分回答了你的问题如果有其他细节需要说明,请将这些细节添加到您的问题中(并在这里对我的答案留下评论,让我知道),我会尝试将它们纳入我的答案中。但是@Ravisenoy的代码是否会工作,如果他在开始时删除变量声明?@Anurag不,可能不会。这些变量只在包含它们的
元素中有作用域,我很确定这不是他想要使用它们的地方。