1

是众所周知的 XSLT 1.0 标识模板

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

同义词

<xsl:template match="/|@*|*|processing-instruction()|comment()|text()">
  <xsl:copy>
    <xsl:apply-templates select="@*|*|processing-instruction()|comment()|text()"/>
  </xsl:copy>
</xsl:template>

即 node() 在 match 语句中包含 / 而在 select 语句中不包含 / 是否正确?

4

1 回答 1

3

节点测试没有不同的node()行为,具体取决于它是在 amatch还是在select属性中。身份模板的扩展版本如下:

<xsl:template match="@*|*|processing-instruction()|comment()|text()">
  <xsl:copy>
    <xsl:apply-templates select="@*|*|processing-instruction()|comment()|text()"/>
  </xsl:copy>
</xsl:template>

node()node-test 匹配任何节点,但是当它没有给出明确的轴时,它child::默认在轴上。所以模式match="node()"不匹配文档根或属性,因为它们不在任何节点的子轴上。

您可以观察到标识模板与根节点不匹配,因为它没有输出:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="yes"/>

    <xsl:template match="@* | node()">
      <xsl:if test="count(. | /) = 1">
        <xsl:text>Root Matched!</xsl:text>
      </xsl:if>
    </xsl:template>
</xsl:stylesheet>

这会输出“根匹配!”:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="yes"/>

    <xsl:template match="@* | node() | /">
      <xsl:if test="count(. | /) = 1">
        <xsl:text>Root Matched!</xsl:text>
      </xsl:if>
    </xsl:template>
</xsl:stylesheet>

您可以通过在任何具有属性的文档上运行此测试来验证node()测试是否适用于根节点和属性:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes"/>

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

  <xsl:template match="/">
    <xsl:if test="self::node()">
      node() matches the root!
    </xsl:if>
    <xsl:apply-templates select="@* | node()" />
  </xsl:template>

  <xsl:template match="@*">
    <xsl:if test="self::node()">
      node() matches an attribute!
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

这是另一种观察node()测试是否适用于根节点的方法:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes"/>

  <xsl:template match="/*">
    <xsl:value-of select="concat('The root element has ', count(ancestor::node()), 
                                 ' ancestor node, which is the root node.')"/>
  </xsl:template>
</xsl:stylesheet>
于 2013-04-22T21:33:14.667 回答