Dave
Dave

Reputation: 19320

XPath: How do I select text() or a span element within a parent element

I have a parent element (font) and I would like to select all the child elements (direct descendants) that are either text() or span elements. How would I construct such an xpath?

Upvotes: 0

Views: 5353

Answers (1)

MiMo
MiMo

Reputation: 11983

If the current node is the font element, then something like this:

text()|span

otherwise you have to always combine with | the two complete XPath - the one for text and the one for span, e.g.:

font/text()|font/span

if the current node is just above font - or

//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/span|//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/text()

if starting from the root with some complex selection criteria.

If you have complex paths like the last one probably it is better to store a partial one in a variable - e.g. inside an XSLT:

<xsl:variable name="font" select="//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font"/>

. . . 

<xsl:for-each select="$font/span|$font/text()">
  . . . 
</xsl:for-each>

Another possibility is to do something like this:

//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/node()[name()='span' or name()='']

that works because name() returns an empty string for text() nodes - but I am not 100% sure that it works that way for all XPath processors, and it could match by mistake comment nodes.

Upvotes: 3

Related Questions