1

I have this xpath expression that does not work

"//div[child[0]::h4[text()[contains(.,'Dir')]]]/a"

To parse this html:

<div class="txt"> 
      <h4 class="c1"> 
        Dir
      </h4> 
    <a  href="/name/myname/">Bob</a>
</div> 

I am trying to get at the link node (a). There are other html tags in the document with the same div/h4 hierarchy, with the only difference being the innertext of the h4 tag. So how do I check that the div class (1) has a sub h4 node with inner text "dir" AND (2) get the first link node (a). Do not assume the link is the next sibling of h4.

1
  • You were very close, except that you can't put a predicate on an axis, so child[0]:: is incorrect. If you wanted the first h4 child of div, you could use //div[child::h4[1][text()[...]]/a, or just //div[h4[1][text()[...]]/a since child:: is implicit for elements. If the h4 must be the first element child, then //div[*[1]/self::h4[...]]/a. Commented Jul 26, 2011 at 16:24

2 Answers 2

2

Couldn't you just use this xpath?

"//div[h4[contains(text(),'Dir')]]/a"

child[0] is not a valid axis AFAIK so it fails.

I don't know if this alone would satisfy your conditions without seeing a more complete example HTML. But this certainly works for this one.

If it's possible that there are multiple h4 elements within the div and you only want to check the first:

"//div[h4[1][contains(text(),'Dir')]]/a"
Sign up to request clarification or add additional context in comments.

1 Comment

Note: I've made the assumption that you will be using the SelectSingleNode() method with these xpaths. So if there are multiple a elements, this will already take the first of them (as required).
1

How do I check that the div class (1) has a sub h4 node with inner text "dir" AND (2) get the first link node (a)

use:

"//div[@class='txt' and h4[contains(.,'Dir')]]/a[1]"

2 Comments

Agree, except you probably don't need the [1] after h4. Or are you inferring that from the OP's child[0]::h4?
@LarsH your observation is logically coherent. h4 is enough as we are using it as conditional. OP asked for a sub h4 not the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.