2010-09-22 108 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>