使用 xpath 函数 contains 将是可行的方法,但解决此问题的一种方法是使用模板进行匹配,而不是使用 xsl:choose你想要的案例。因此,您首先要查找任何 link 元素
<xsl:apply-templates select="link"/>
然后您将有一个模板来匹配 @href 属性包含一个命令的 link 元素
<xsl:template match="link[contains(@href, ',')]">
您还需要一个更通用的模板来匹配所有其他 link 元素。只有在其他更具体的模板没有找到匹配项时才会匹配
<xsl:template match="link">
例如,考虑以下 XML
<root>
<doc>
<link href="http://www.example.com" />
</doc>
<doc>
<link href="http://www.example1.com,http://www.example2.com" />
</doc>
</root>
当您应用以下 XSLT 时
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="root">
<table>
<tr>
<xsl:apply-templates select="doc"/>
</tr>
</table>
</xsl:template>
<xsl:template match="doc">
<xsl:apply-templates select="link"/>
<xsl:if test="not(link[@href])">
<td>No link</td>
</xsl:if>
</xsl:template>
<xsl:template match="link[contains(@href, ',')]">
<td class="link2">
<xsl:call-template name="link">
<xsl:with-param name="href" select="substring-before(@href, ',')"/>
</xsl:call-template>
<xsl:call-template name="link">
<xsl:with-param name="href" select="substring-after(@href, ',')"/>
</xsl:call-template>
</td>
</xsl:template>
<xsl:template match="link">
<td class="link">
<xsl:call-template name="link"/>
</td>
</xsl:template>
<xsl:template name="link">
<xsl:param name="href" select="@href"/>
<a href="{$href}">
<xsl:copy-of select="$href"/> Link</a>
</xsl:template>
</xsl:stylesheet>
那么下面是输出
<table>
<tr>
<td class="link">
<a href="http://www.example.com"> Link</a>
</td>
<td class="link2">
<a href="http://www.example1.com">http://www.example1.com Link</a>
<a href="http://www.example2.com">http://www.example2.com Link</a>
</td>
</tr>
</table>
注意,这也使用了命名模板来避免重复代码。
编辑:如果您有多个元素,以及具有 @href 属性的 link,那么您可以通过多种方式来做到这一点。如果你的名字数量有限,你可以这样做
<xsl:apply-templates select="link|website|localpath" />
然后你可以像这样匹配它们......
<xsl:template match="link[contains(@href, ',')]|website[contains(@href, ',')]|localpath[contains(@href, ',')]">
<xsl:template match="link|website|website" />
最好是查看任何元素,像这样
<xsl:apply-templates select="*" />
然后匹配任何带有 href 属性的元素,以及那些没有的
<xsl:template match="doc/*[contains(@href, ',')]">
<xsl:template match="doc/*">