简体   繁体   English

如何在xsl:choose中使用xsl:variable

[英]How to use xsl:variable in xsl:choose

Hey I have one xsl variable that I want to use in xsl choose tag 嘿,我有一个要在xsl选择标记中使用的xsl变量

<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="1 eq whatever">
             <xsl:variable name="name" select="Person/Name"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

It will give exception 它将给出异常

javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:828)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:617)
    at com.navaera.sunflower.set.util.XmlElementsBuilder.getXMLOutput(XmlElementsBuilder.java:189)

You are not using the variable name inside xsl:choose - you declare it there. 您没有在xsl:choose 使用变量name -在此处声明它。

To declare a variable inside an xsl:when only makes sense if you also make use of this variable inside the same element. xsl:when内声明变量xsl:when仅当您还在同一元素内使用此变量时才有意义。 This is because of the scope of a variable. 这是因为变量的范围 If you declare a local variable inside xsl:when , you cannot use it outside. 如果在xsl:when内声明局部变量,则不能在外部使用它。

Using xsl:choose only makes sense if you test at least two different conditions, one inside xsl:when , the other in xsl:otherwise . 仅当您测试至少两个不同的条件时才使用xsl:choose才有意义,一个条件在xsl:when内部,另一个条件在xsl:otherwise If there is only one condition, xsl:if will suffice. 如果只有一个条件,则xsl:if就足够了。

If you reveal more of your XSLT stylesheet it might be possible to tell where you went wrong. 如果您揭示了更多的XSLT样式表,则可能可以判断出哪里出错了。 So, please update your question with a complete input XML and a complete XSLT stylesheet. 因此,请使用完整的输入XML和完整的XSLT样式表来更新您的问题。

EDIT : To make this even clearer: No, it is not possible to use a local variable outside of its scope. 编辑 :使其更加清楚:不,不可能在其范围之外使用局部变量。 If you declare a variable inside xsl:when you'll never be able to access it outside. 如果在xsl:when声明变量,则永远无法在外部访问它。

you can use a global variable 您可以使用全局变量

<xsl:variable name="name" select="Person/Name"/>

and call it inside a template 并在模板中调用它

<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="1 eq whatever">
             <xsl:value-of select="$name"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

If you ask the question "I want to write + 3 5", you will get the answer "you can't do that, the language doesn't allow it". 如果您问“我要写+ 3 5”问题,您将得到答案“您不能这样做,语言不允许这样做”。 If you change the question to "I want to add three to five", people will tell you to write "3 + 5". 如果您将问题更改为“我想加三到五”,人们会告诉您写“ 3 + 5”。 So please explain your problem, and then we can tell you the right way to code it. 因此,请解释您的问题,然后我们可以告诉您正确的编码方式。 We can't work out what the problem is by looking at incorrect code. 通过查看错误的代码,我们无法解决问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM