在 XSL 中:如何避免用于包装元素的选择块? [英] In XSL: How to avoid choose-blocks for wrapping elements?

查看:27
本文介绍了在 XSL 中:如何避免用于包装元素的选择块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种情况,经常出现.我正在解析 XML 并通过 XSLT 1.0 生成我的 XHTML 文档.

there is a case, that appears often times. I am parsing an XML and generate my XHTML document via XSLT 1.0.

案例:

/* 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 集,我只是在获取案例.我对这种方法不满意,但我看不到实现此方法的另一种选择.

You see the problem: I am just fetching the case if there is a href set. I'm not satisfied with this approach, but I don't see another option for implementing this.

有什么想法吗?

推荐答案

消除模板内显式条件指令的方法是在模板的匹配模式中使用模式匹配::>

<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: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>

这篇关于在 XSL 中:如何避免用于包装元素的选择块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆