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

ぐ巨炮叔叔 提交于 2021-01-27 13:21:40

问题


Is there a difference between the following two xpath expressions?

  • child::*
  • child::node()

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.


回答1:


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 and a node.

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>
    


来源:https://stackoverflow.com/questions/52045856/xpath-difference-between-child-and-childnode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!