Only select text directly in node, not in child nodes

后端 未结 3 1816
余生分开走
余生分开走 2021-01-30 13:06

How does one retrieve the text in a node without selecting the text in the children?

Editor\'s Descrip
3条回答
  •  星月不相逢
    2021-01-30 13:25

    In the provided XML document:

    Editor's Description
    Last updated:

    Lorem ipsum dolor sit amet.

    the top element /div has 4 children nodes that are text nodes. The first three of these four text-node children are whitespace-only. The last of these 4 text-node children is the one that is wanted.

    Use:

    /div/text()[last()]
    

    This is different from:

    /div/text()
    

    The latter may (depending on whether whitespace-only nodes are preserved by the XML parser) select all 4 text nodes, but you only want the last of them.

    An alternative is (when you don't know exactly which text-node you want):

    /div/text()[normalize-space()]
    

    This selects all text-node-children of /div that are not whitespace-only text nodes.

提交回复
热议问题