2017-03-29 57 views
1

我在解析XSLT中的變量時遇到問題。我有一個帶有固定值的工作XSL文件,現在我想使其動態變化(變量聲明將在XSL文件運行之後移出)。我目前的問題是在starts-with函數中使用變量$。這就是所有Google使用的方式讓我相信它應該看起來,但它不會編譯。它適用於我在substring-after函數中使用它。這應該怎麼做?在XSLT中解析變量

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:variable name="oldRoot" select="'top'" /> 
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" /> 
<xsl:variable name="newRoot" select="'newRoot'" /> 

    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 

<xsl:template match="bind/@ref[starts-with(., $beginning)]"> 
    <xsl:attribute name="ref"> 
     <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of> 
     <xsl:value-of select="substring-after(., $beginning)" /> 
    </xsl:attribute> 
</xsl:template> 
</xsl:stylesheet> 
+0

「不會編譯」 - 下一次,你可以節省大家如果你告訴我們錯誤信息是什麼,他會稍微閱讀一下這段時間。當然,邁克爾, –

+0

。會「無法調試文檔,無法編譯樣式表,檢測到1個錯誤。」給了你更多的信息? –

+1

它不直接給我更多的信息,但它可以幫助我幫助你。它告訴我,您可能正在運行Saxon(大概6.5,因爲這可以用於XSLT 2.0),並且它告訴我您可能錯誤地運行了處理器,因爲您沒有看到真正的錯誤消息。我會提出一個新問題:爲什麼我沒有看到真正的錯誤信息?因爲除非你解決這個問題,否則你會發現樣式表開發非常困難。 –

回答

2

在XSLT 1.0它被認爲是對一個模板匹配表達式包含一變量(見https://www.w3.org/TR/xslt#section-Defining-Template-Rules)的誤差,所以這條線出現故障

<xsl:template match="bind/@ref[starts-with(., $beginning)]"> 

(I相信一些處理器可以允許的話,但是如果他們遵循這個規範,他們不應該這樣做,但是在XSLT 2.0中允許)。

你可以做的是移動狀態的模板中,並與xsl:choose

處理一下試試這個XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:variable name="oldRoot" select="'top'" /> 
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" /> 
<xsl:variable name="newRoot" select="'newRoot'" /> 

<xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="bind/@ref"> 
    <xsl:choose> 
     <xsl:when test="starts-with(., $beginning)"> 
      <xsl:attribute name="ref"> 
       <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of> 
       <xsl:value-of select="substring-after(., $beginning)" /> 
      </xsl:attribute> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:copy-of select="." /> 
     </xsl:otherwise>    
    </xsl:choose> 
</xsl:template> 
</xsl:stylesheet> 
+0

非常感謝蒂姆! –