2010-09-22 106 views
4

我打電話模板:如何從更深的層次訪問root屬性在XSLT

<table> 
    <xsl:apply-templates select="data/pics/row"/> 
</table> 

模板是

<xsl:template match="row"> 
    <tr> 
     <xsl:for-each select="td"> 
      <td border="0"> 
       <a href="{@referencddePage}"> 
        <img src="{pic/@src}" width="{pic/@width}" height="{pic/@height}"/> 
       </a> 
      </td> 
     </xsl:for-each> 
    </tr> 
</xsl:template> 

我的XML是:

<?xml version="1.0" encoding="iso-8859-8"?> 
<?xml-stylesheet type="text/xsl" href="xslFiles\smallPageBuilder.xsl"?> 
<data pageNo="3" referencePage="xxxxxxxxxxxxxxx.xml"> 
    <pics> 
     <row no="0"> 
      <td col="0"> 
       <pic src="A.jpg" width="150" height="120"></pic> 
      </td> 
     </row> 
    </pics> 
</data> 

我想要行:a h r e f="{@referencddePage}"從 獲得輸入的根,,但我已經在<td level>

+0

問得好(+1)。請參閱我的答案,以獲得既簡單又完全符合XSLT精神的解決方案,主要使用「推式」。 – 2010-09-22 02:22:14

回答

2

我想要這行:ahre f =「{@ referencddePage}」從根目錄獲取 輸入:ahref = 「{@referencdde頁}」 ......但我在<td level>

如果 已經是一個規則,即@referencePage屬性始終是頂級元素的屬性,那麼它總是可以作爲訪問:

/*/@referencePage 

因此,在你的代碼,就必須:

<a href="{/*/@referencePage}"> 

我會建議不要使用<xsl:for-each>和只使用and'。以這種方式所得到的XSLT代碼是更容易理解,並且可以在將來更容易地修改:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 
<xsl:template match="row"> 
    <tr> 
    <xsl:apply-templates/> 
    </tr> 
</xsl:template> 

<xsl:template match="td"> 
    <td border="0"> 
    <a href="{/*/@referencePage}"> 
     <xsl:apply-templates/> 
    </a> 
    </td> 
</xsl:template> 

<xsl:template match="pic"> 
    <img src="{@src}" width="{@width}" height="{@height}"/> 
</xsl:template> 
</xsl:stylesheet> 

當這個變換所提供的XML文檔應用,

<data pageNo="3" referencePage="xxxxxxxxxxxxxxx.xml"> 
    <pics> 
    <row no="0"> 
     <td col="0"> 
     <pic src="A.jpg" width="150" height="120"></pic> 
     </td> 
    </row> 
    </pics> 
</data> 

有用輸出產生:

<tr> 
    <td border="0"> 
     <a href="xxxxxxxxxxxxxxx.xml"> 
     <img src="A.jpg" width="150" height="120"/> 
     </a> 
    </td> 
</tr> 

看看每個模板如何非常簡單。此外,代碼進一步簡化。

代替

現在:

<img src="{pic/@src}" width="{pic/@width}" height="{pic/@height}"/> 

我們只有:

<img src="{@src}" width="{@width}" height="{@height}"/> 
+0

+1適用於推式 – 2010-09-22 13:05:21

0

使用XPath說,「跳」到了領先的斜線文檔的頂部,然後往下走樹:

/data/@referencePage

把它應用到你的樣式表:

<xsl:template match="row"> 
    <tr> 
     <xsl:for-each select="td"> 
      <td border="0"> 
       <a href="{/data/@referencePage}"> 
        <img src="{pic/@src}" width="{pic/@width}" height="{pic/@height}"/> 
       </a> 
      </td> 
     </xsl:for-each> 
    </tr> 
</xsl:template>