SiberianGuy
SiberianGuy

Reputation: 25302

XPATH filter tag-less children

Is there any way to specify that I want to select only tag-less child elements (in the following example - "text")?

<div>
   <p>...</p>
   "text"
</div>

Upvotes: 2

Views: 546

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

Use:

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

This selects all text nodes that are children of the top element of the document and that do not consist only of white-space characters.

In the concrete example this will select only the text node with string value:

'
       "text"
    '

The XPath expressions:

/*/text()

or

/div/text()

both select two text nodes, the first of which contains only white-space and the second is the same text node as above:

'
       "text"
    '

Upvotes: 1

jasso
jasso

Reputation: 13966

select only tag-less child elements

To me this sounds like selecting all elements that don't have other elements as children. But then again, "text" in your example is not an element, but a text node, so I'm not really sure what do you want to select... Anyway, here is a solution for selecting such elements.

//*[not(*)]

Selects all elements that don't have an element as a child. Replace the first * with an element name if you only want to select certain elements that don't have child elements. Also note that using // is generally slow since it runs through the whole document. Consider using more specific path when possible (like /div/*[not(*)] in this case).

Upvotes: 0

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

The text() function matches text nodes. Example: //div/text() — matches all text children within all div elements.

Upvotes: 3

Related Questions