XSL Variable Assignment/Usage

后端 未结 3 1081
闹比i
闹比i 2021-01-14 12:46

I have an XML file I\'m processing with XSL to build a PDF. I\'m running into an issue when I try to use an XSL variable. I\'m not sure if I\'m using it in the wrong scope,

相关标签:
3条回答
  • 2021-01-14 12:52

    The error message suggests that you are using XSLT 2.0, so you can simply write:

    <xsl:template name="article-meta-details">
        <xsl:call-template name="subtitle">
          <xsl:with-param name="text" 
            select="if (/article-meta/oldedition = 1) then 'Old' else 'New'" />
        </xsl:call-template>
    </xsl:template>
    
    0 讨论(0)
  • 2021-01-14 13:01

    If someone could please point out what I'm doing wrong

    The main problem with your approach is scope. When you define a variable like this:

    <xsl:when test="/article-meta/oldedition = 1"> 
        <xsl:variable name="section_title" select="'Old'"/>
    </xsl:when>
    

    it exists only until you close the xsl:when element. Similarly, the other variable exists only within the xsl:otherwise tags. (If it weren't so, the two would collide, having the same name.)

    and/or how to resolve it

    It's hard to advise without seeing the wider picture, but couldn't you do simply:

    <xsl:template name="article-meta-details">
        <xsl:call-template name="subtitle">
            <xsl:with-param name="text">
                <xsl:choose>
                    <xsl:when test="/article-meta/oldedition = 1">Old</xsl:when>
                    <xsl:otherwise>New</xsl:otherwise>
                </xsl:choose>
        </xsl:call-template>
        <!-- more? -->
    </xsl:template>
    
    0 讨论(0)
  • 2021-01-14 13:08

    This is because you're approaching variable declaration as you might in a procedural language.

    XSLT is compiled, and so it needs to be sure that your variable either exists or it doesn't. It sees you declaring it conditionally, and it gets worried.

    Simply make the variable value conditional, rather than the variable's existence itself.

    <xsl:variable name="section_title">
        <xsl:choose>
            <xsl:when test="/article-meta/oldedition = 1">Old</xsl:when>
            <xsl:otherwise>New</xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    
    0 讨论(0)
提交回复
热议问题