【问题标题】:Self-closing xsl:template tag?自动关闭 xsl:template 标签?
【发布时间】:2017-08-24 18:44:38
【问题描述】:

我正在查看一个旧的 xsl 文件并试图了解为什么原作者将许多 <xsl:template> 元素定义为包含 match 属性的 自闭合标签。在下面的示例中,我的问题是关于<xsl:template match="title" />

XML

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
</catalog>

XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
      <html>
          <body>
              <h2>My CD Collection</h2>  
              <xsl:apply-templates/>  
          </body>
      </html>
    </xsl:template>

    <xsl:template match="cd">
        <p>
            <xsl:apply-templates select="title"/>  
            <xsl:apply-templates select="artist"/>
        </p>
    </xsl:template>

    <xsl:template match="title" />

    <xsl:template match="artist">
        Artist: <span style="color:#00ff00">
                <xsl:value-of select="."/></span>
        <br />
    </xsl:template>
</xsl:stylesheet>

由于标签是自动关闭的,&lt;xsl:template \&gt; 中显然没有内容。这样做有什么意义?这是一种通过 match 属性“隐藏”与template 关联的 XML 数据的技术吗?

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    自关闭xsl:template 标签用于抑制匹配的节点。这通常与身份转换结合使用,以便将其他所有内容复制到输出除了被抑制的节点。

    例如,&lt;xsl:template match="title" /&gt; 不会对输入文档中匹配的 title 元素执行任何操作。

    【讨论】:

      【解决方案2】:

      在显式使用&lt;xsl:apply-templates select="title"/&gt; 然后还使用&lt;xsl:template match="title" /&gt; 以确保title 元素不产生输出的样式表中没有多大意义,但在例如&lt;xsl:apply-templates select="*"/&gt; 或只是 &lt;xsl:apply-templates/&gt;cd 父模板中,然后您可以使用空的 &lt;xsl:template match="title" /&gt; 来确保 title 元素不会产生任何输出。

      在给定的样式表中,简单地删除&lt;xsl:apply-templates select="title"/&gt;当然会更容易。

      常与身份转换模板一起使用的地方

      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
      

      然后您可以添加一些模板来转换某些元素,并且您可以添加空模板(例如&lt;xsl:template match="title" /&gt;)来删除其他元素(例如title 元素),因为这样它们不会产生任何输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-16
        • 2018-05-17
        • 2013-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多