Xeoncross
Xeoncross

Reputation: 57194

Get parent element name in XPath

I am trying to figure out how to get the name of the parent from a text node's scope.

//text()[name(parent)='p']

How can you get the name of the current node's parent?

Upvotes: 9

Views: 19720

Answers (3)

LarsH
LarsH

Reputation: 27994

FYI, point of terminology: a text node is not an element.

Anyway, the most succinct way to select the parent of the current node is ..

So, the name of the parent element of the current node (which could be a text node) is name(..)

Substituting that into your XPath expression:

//text()[name(..)='p']

But a less roundabout way to write that would be

//p/text()

(assuming the p elements in the document have no namespace prefix). Either way, you're selecting all text nodes that are children of elements named p.

Upvotes: 4

Daniel Haley
Daniel Haley

Reputation: 52858

If you're trying to test the name, you almost had it:

//text()[name(parent::*)='p']

If you're trying to return the name:

name(//text()/parent::*)

Upvotes: 18

Jonathan M
Jonathan M

Reputation: 17451

//text/..[@name='p']

This will get all parents of <text> nodes as long as the parent has a name attribute of p.

Upvotes: 1

Related Questions