XPath to find the text of a node that is a native friend of other nodes

Given the following html snippet:

<fieldset>
  <legend>My Legend</legend>
  <p>Some text</p>
  Text to capture
</fieldset>

      

Is there an xpath expression that will return the text 'Text to capture' node?

Attempt

/ fieldset / text ()
gives three nodes, not just the one I need.
+2


a source to share


2 answers


Assuming you want a text node that contains text without spaces:

//fieldset/text()[normalize-space(.)]

      



If you want the last node text then:

//fieldset/text()[last()]

      

+7


a source


I recommend that you accept Steven D. Mayevsky's answer, but here's the explanation (text nodes are in square brackets):

<fieldset>[
  ]<legend>My Legend</legend>[
  ]<p>Some text</p>[
  Text to capture
]</fieldset>

      

so /fieldset/text()

returns



  • "\n "

  • "\n "

  • "\n Text to capture\n"

And that's why you want /fieldset/text()[normalize-space()]

, and you want, the result to be truncated before use.

Also note that the above is not valid for /fieldset/text()[normalize-space(.) != '']

. When it normalize-space()

returns a non-empty string, the predicate evaluates to true

, and the empty string evaluates to false

.

+7


a source







All Articles