Alfe
Alfe

Reputation: 59426

XPath expression for finding the current element as well as children

With the expression .//b I can find all elements below the current element with the tag b. If the current element has also a b tag, it will not be found. How can I express that I want to find all the children of the current tag as well as the current element itself, in case it matches the given tag name?

Here is some example input xml:

<a>
  <b>
    <i>
      <u>one</u>
    </i>
    <b>two</b>
  </b>
  <b>three</b>
  <em>four</em>
</a>

If the first element <b> is the current element, I want to get all sub elements (i. e. the one containing two) and the element itself, but not the element containing three (when searching for tags b). When searching for tags u I want to get only the one containing one.

I've tried .[name()='b']|.//b but that's apparently an invalid expression.

I also tried ..//b but then I not only get the element itself and the one containing two but also the one containing three.

Is this possible with one XPath expression to get what I want?

Side note: I'm using this in Python's lxml/etree library but that should make no difference.

Upvotes: 0

Views: 394

Answers (1)

Tim C
Tim C

Reputation: 70618

You want to use the descendant-or-self axis here:

descendant-or-self::b

Alternatively, you could do this, which is slightly shorter to write...

self::b|.//b

Upvotes: 3

Related Questions