我有以下模板
<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>
如果相应模板至少有一个成员,我只想显示标题(一、二、三)。我该如何检查?
<xsl:if test="one">
<h2>one</h2>
<xsl:apply-templates select="one"/>
</xsl:if>
<!-- etc -->
或者,您可以创建一个命名模板,
<xsl:template name="WriteWithHeader">
<xsl:param name="header"/>
<xsl:param name="data"/>
<xsl:if test="$data">
<h2><xsl:value-of select="$header"/></h2>
<xsl:apply-templates select="$data"/>
</xsl:if>
</xsl:template>
然后调用为:
<xsl:call-template name="WriteWithHeader">
<xsl:with-param name="header" select="'one'"/>
<xsl:with-param name="data" select="one"/>
</xsl:call-template>
但老实说,这对我来说似乎更多的工作......只有在绘制标题很复杂时才有用......对于一个简单的<h2>...</h2>
我很想把它留在内联。
如果标题标题始终是节点名称,您可以通过删除“$header”参数来简化模板,并改用:
<xsl:value-of select="name($header[1])"/>
我喜欢练习 XSL 的功能方面,这导致我进行以下实现:
<?xml version="1.0" encoding="UTF-8"?>
<!-- test data inlined -->
<test>
<one>Content 1</one>
<two>Content 2</two>
<three>Content 3</three>
<four/>
<special>I'm special!</special>
</test>
<!-- any root since take test content from stylesheet -->
<xsl:template match="/">
<html>
<head>
<title>Header/Content Widget</title>
</head>
<body>
<xsl:apply-templates select="document('')//test/*" mode="header-content-widget"/>
</body>
</html>
</xsl:template>
<!-- default action for header-content -widget is apply header then content views -->
<xsl:template match="*" mode="header-content-widget">
<xsl:apply-templates select="." mode="header-view"/>
<xsl:apply-templates select="." mode="content-view"/>
</xsl:template>
<!-- default header-view places element name in <h2> tag -->
<xsl:template match="*" mode="header-view">
<h2><xsl:value-of select="name()"/></h2>
</xsl:template>
<!-- default header-view when no text content is no-op -->
<xsl:template match="*[not(text())]" mode="header-view"/>
<!-- default content-view is to apply-templates -->
<xsl:template match="*" mode="content-view">
<xsl:apply-templates/>
</xsl:template>
<!-- special content handling -->
<xsl:template match="special" mode="content-view">
<strong><xsl:apply-templates/></strong>
</xsl:template>
一旦进入正文,测试元素中包含的所有元素都应用了header-content-widget(按文档顺序)。
默认的header-content-widget模板(匹配“*”)首先应用header-view,然后将content-view应用到当前元素。
默认的header-view模板将当前元素的名称放在 h2 标记中。默认内容视图应用通用处理规则。
当[not(text())]谓词判断没有内容时,不会出现该元素的输出。
一种特殊情况很容易处理。