d4rty
d4rty

Reputation: 4188

XPath difference between child::* and child::node()

Is there a difference between the following two xpath expressions?

I tried both expressions on this playground page and got the same result.

W3schools says

child::* Selects all element children of the current node

child::node() Selects all children of the current node

but I do not get the difference.

Upvotes: 4

Views: 725

Answers (1)

kjhughes
kjhughes

Reputation: 111541

Both child::* and child::node() refer to the children of the current node, so the difference is really in the difference between that of an element (for which * selects any), and a node (for which node() selects any).

An element is a type of node.

XPath has the following node types in its model of XML:

  • element
  • attribute
  • text
  • namespace
  • processing instruction (PI)
  • comment
  • root

For your example XML / HTML,

<html>
    <head>
        <title>My page</title>
    </head>
    <body>
        <h2>Welcome to my <a href="#">page</a></h2>
        <p>This is the first paragraph</p>.
        <!-- this is the end -->
    </body>
</html>

there are count(//*) = 7 elements and count(//node()) = 21 nodes.

Your playground XPath is //h2/a, which doesn't really illustrate child::* vs child::node().

If instead you consider //h2/* vs //h2/node(), then

  • //h2/* selects a single node, an element:

      <a href="#">page</a>
    
  • //h2/node() selects two nodes, a text node and an element:

      Welcome to my
      <a href="#">page</a>
    

Upvotes: 4

Related Questions