有一种情况经常出现.我正在解析XML并通过XSLT 1.0生成我的XHTML文档.
案件:
/* XML */
<Image src="path-to-img.jpg" href="link-to-page.html" />
/* XSL */
<xsl:choose>
    <xsl:when test="@href">
    <a href="{@href}">
       <img src="{@src}"/>
    </a>
</xsl:when>
<xsl:otherwise>
    <img src="{@src}"/>
</xsl:otherwise>
</xsl:choose>
你看到了问题:如果有一个href设置,我只是提取案例.我对这种方法不满意,但我没有看到实现这一点的另一种选择.
有任何想法吗?
消除模板中显式条件指令的方法是在模板的匹配模式中使用模式匹配:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:template match="Image[@href]">
    <a href="{@href}">
     <xsl:call-template name="basicImage" />
    </a>
 </xsl:template>
 <xsl:template match="Image" name="basicImage">
   <img src="{@src}"/>
 </xsl:template>
</xsl:stylesheet>
XSLT 2.0:有一个特别优雅的解决方案<xsl:next-match>:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:template match="Image[@href]">
    <a href="{@href}">
    <xsl:next-match/>
    </a>
 </xsl:template>
 <xsl:template match="Image" name="basicImage">
   <img src="{@src}"/>
 </xsl:template>
</xsl:stylesheet>
这两种转换在应用于提供的XML文档时:
<Image src="path-to-img.jpg" href="link-to-page.html" />
产生想要的,正确的结果:
<a href="link-to-page.html">
   <img src="path-to-img.jpg"/>
</a>
| 归档时间: | 
 | 
| 查看次数: | 571 次 | 
| 最近记录: |