如何在XSLT中检查标签是否存在?

9
我有以下模板
<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>

我希望只有至少一个相应模板的成员时,才显示标题(one,two,three)。我该如何检查这一点?

你的XML文件是什么样子的?你想在哪个文件上使用这个模板? - kender
2个回答

15
<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])"/>

2

我喜欢运用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>

body 中,test 元素内的所有元素都应用了 header-content-widget(按文档顺序)。

默认的 header-content-widget 模板(匹配“*”)首先应用一个 header-view,然后将一个 content-view 应用于当前元素。

默认的 header-view 模板将当前元素的 name 放置在 h2 标签中。默认的 content-view 应用通用处理规则。

当通过 [not(text())] 谓词判断没有内容时,元素不会输出。

一次性的 特殊 情况很容易处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接