Difference between * and node() in XSLT

2019-02-04 11:28发布

问题:

What's the difference between these two templates?

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

<xsl:template match="*">

回答1:

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

is an abbreviation for:

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

This matches any node type that can be selected via the child:: axis:

  • element

  • text-node

  • processing-instruction (PI) node

  • comment node.

On the other side:

<xsl:template match="*">

is an abbreviation for:

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

This matches any element.

The XPath expression: someAxis::* matches any node of the primary node-type for the given axis.

For the child:: axis the primary node-type is element.



回答2:

Just to illustrate one of the differences, viz that * doesn't match text:

Given xml:

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

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

Gives:

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

Whereas matching on *:

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

Doesn't match the text nodes.

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


回答3:

Also refer to XSL xsl:template match="/" for other match patterns.