2011-10-25 33 views
2

還有另外一個類別實驗室測驗我需要使用XSLT 1.0比較position()返回值和參數值的幫助。我有下面這段簡單的XML ...XSLT 1.0 - 如何將位置()返回值與參數值進行比較

<Providers> 
    <Company> 
     <Name>Alpha</Name> 
    </Company> 

    <Company> 
     <Name>Beta</Name> 
    </Company> 

    <Company> 
     <Name>Omega</Name> 
    </Company> 
</Providers> 

而且我想在一個參數來傳遞一個數值,指定哪個節點級插入一個名爲評級喜歡這個新元素...

<Providers> 
     <Company> 
       <Name>Alpha</Name> 
     </Company> 

     <Company> 
       <Name>Beta</Name> 
       <Rating>Good</Rating> 
     </Company> 

     <Company> 
       <Name>Omega</Name> 
     </Company> 
</Providers> 

這裏是我的XSLT ...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output indent="yes"/> 
    <xsl:strip-space elements="*"/> 

<xsl:param name="nodeNumber">2</xsl:param> 


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


<xsl:template match="Providers"> 
    <xsl:copy> 
     <xsl:apply-templates /> 
    </xsl:copy> 
</xsl:template> 


<xsl:template match="Company[ position() = 2 ]"> 
    <xsl:copy> 
     <xsl:copy-of select="@*|node()"/> 
     <Rating>Good</Rating> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

而不是硬編碼到第二個節點...

<xsl:template match="Company[ position() = 2 ]"> 

我想要做這樣的比較,所以它使用的參數值...

<xsl:template match="Company[ position() = $nodeNumber ]"> 

,但我得到一個錯誤,如果XSLT 1.0 ...

c:\ msxsl.exe providers.xml providers.xsl 

Error occurred while compiling stylesheet 'providers.xsl'. 

Code: 0x80004005 
Variables may not be used within this expression. 

Company[ position() = -->$nodeNumber <--] 

它工作正常,如果XSLT是2.0 ...

c:\ altovaxml.exe /xslt2 providers.xsl /in providers.xml 

<?xml version="1.0" encoding="UTF-8"?> 
<Providers> 
     <Company> 
       <Name>Verizon</Name> 
     </Company> 
     <Company> 
       <Name>Sprint</Name> 
       <Rating>Good</Rating> 
     </Company> 
     <Company> 
       <Name>ATT</Name> 
     </Company> 
</Providers> 

我需要使用XSLT 1.0。非常感謝你的時間和精力...

回答

3
<xsl:template match="Company"> 
    <xsl:copy> 
    <xsl:copy-of select="@*|node()"/> 
    <xsl:if test="(count(preceding-sibling::Company) + 1) = $nodeNumber"> 
     <Rating>Good</Rating> 
    </xsl:if> 
    </xsl:copy> 
</xsl:template> 
+0

嘿,非常感謝你,它的工作!感謝您花時間閱讀我的問題併發布答案! –

+2

你已經接受了答案,但它是錯誤的。在匹配模式的謂詞中調用position()測試節點相對於其同名兄弟的位置,而模板主體中的position()是在相應的應用模板中選擇的節點集合中的位置呼叫。 –

+0

@MichaelKay有用,請更改爲'(count(prior-sibling :: Company)+ 1)= $ nodeNumber'。 –

相關問題