xslt - 什么是node()的显式版本

标签 xslt xpath xslt-1.0 xmlnode apply-templates

是著名的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语句中不包含/是否正确?

最佳答案

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

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


node()节点测试与任何节点匹配,但是当未为它指定显式轴时,默认情况下它位于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>


并输出“ Root Match!”:

<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()测试,以验证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>


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

<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>

关于xslt - 什么是node()的显式版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155940/

相关文章:

xml - 在 FO 中将多个 block 容器渲染为内联

php - 尽管XSL样式表几乎为空,但XSLTProcessor::importStylesheet()中的PHP警告

java - 在 Wildfly 8.1 中设置 javax.xml.transform.TransformerFactory

javascript - 将多个 xsl 模板与一个 xml 一起使用

xml - 当值是多个或缺失时来自 XML 的 R 数据框

xslt - 这个 XSLT 片段可以更简洁吗?

xml - 使用 XSLT 1.0 将 XHTML 转换为结构化 XML

java - 为运行时 spring-context 建模引用文档和渲染引擎

python - 请求响应的 Xpath 返回空列表

html - xpath 选择 td 的以下兄弟内容图像与 alt