XSLT中*和node()之间的区别是什么?

32

这两个模板有什么区别?

<xsl:template match="node()">

<xsl:template match="*">

这个答案也适用:https://dev59.com/8W035IYBdhLWcg3wef9y - StuartLC
3个回答

44
<xsl:template match="node()">

是以下缩写的简称:

<xsl:template match="child::node()">

这将匹配可以通过child::轴选择的任何节点类型::

  • 元素

  • 文本节点

  • 处理指令(PI)节点

  • 注释节点。

另一方面:

<xsl:template match="*">

是以下缩写的简称:

<xsl:template match="child::*">

这匹配任何元素

XPath表达式:someAxis::*匹配给定轴的主节点类型的任何节点。

对于child::轴,主节点类型是元素


17

仅为说明其中的一个差异,即*不匹配text:

给定的xml:

<A>
    Text1
    <B/>
    Text2
</A>

使用 node() 进行匹配

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

    <!--Suppress unmatched text-->
    <xsl:template match="text()" />

    <xsl:template match="/">
        <root>
            <xsl:apply-templates />
        </root>
    </xsl:template>

    <xsl:template match="node()">
        <node>
            <xsl:copy />
        </node>
        <xsl:apply-templates />
    </xsl:template>
</xsl:stylesheet>

结果为:

<root>
    <node>
        <A />
    </node>
    <node>
        Text1
    </node>
    <node>
        <B />
    </node>
    <node>
        Text2
    </node>
</root>

在使用 * 进行匹配时:

<xsl:template match="*">
    <star>
        <xsl:copy />
    </star>
    <xsl:apply-templates />
</xsl:template>

不匹配文本节点。

<root>
  <star>
    <A />
  </star>
  <star>
    <B />
  </star>
</root>

3
* 不匹配注释节点、处理指令节点、属性节点、命名空间节点和文档节点…… *(作为 child::* 的缩写)的模式或表达式只会匹配元素节点,并且只会匹配元素节点。使用 @*(作为 attribute::* 的缩写),星号仅匹配属性轴上的属性节点。 - Abel

2

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