2017-08-24 97 views
2

我正在查看一个旧的xsl文件,并试图了解为什么原作者已将<xsl:template>元素的数量定义为包含match属性的自关闭标记。在下面我的问题的例子是在问候<xsl:template match="title" />自动关闭xsl:模板标签?

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> 

由于标签是自闭,但显然没有内容在<xsl:template \>。这样做的意义何在?这是一种通过匹配属性“隐藏”与template关联的XML数据的技术吗?

回答

2

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

<xsl:template match="title" />对于在输入文档中匹配的title元素将不起任何作用。

0

在样式表中明确使用<xsl:apply-templates select="title"/>然后也使用<xsl:template match="title" />确保title元素不产生任何输出,但是在例如情况下,没有多少意义。 <xsl:apply-templates select="*"/>或简单<xsl:apply-templates/>cd父母的模板中,然后可以使用空的<xsl:template match="title" />以确保title元素不会产生任何输出。

在给定的样式表中,只需简单地删除<xsl:apply-templates select="title"/>即可。

当它经常被用来为一起与身份转换模板

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

,随后再添加一些模板变换某些元素,你可以添加空的模板(如<xsl:template match="title" />)删除其他元素(如title元素),因为它们不会产生任何输出。