gpt4 book ai didi

xml - 在 XSL : How to avoid choose-blocks for wrapping elements? 中

转载 作者:数据小太阳 更新时间:2023-10-29 01:53:52 24 4
gpt4 key购买 nike

有一种情况,经常出现。我正在解析 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>

关于xml - 在 XSL : How to avoid choose-blocks for wrapping elements? 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7201423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com