XPath element which contains an attribute and whose parent's parent contains another attribute
Asked Answered
L

1

9

This is my first post here and since I've seen many great answers I thought I'd give it a try.

I'm trying to use XPath to obtain a specific element in an HTML document. Here is an example based off of the Google web page:

<html>
  <head>
    <title>XPath Test</title>
  </head>
  <body>
    <form name='f'>
      <table>
        <tbody>
          <tr>
            <td>
              <input name='q' type="text" />
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  </body>
</html>

Using the example above (which is simplified for the purposes of asking for help), I would like to be able to find the input element whose name='q' and who has an ancestor who is 5 parents up with the name='f'.

For example if I were to do this in the syntax of S.W.A.T. which is an open-source web automation testing library located at http://ulti-swat.wikispaces.com, the syntax would be as follows:

|AssertElementExists|Expression|name=q;parentElement.parentElement.parentElement.parentElement.parentElement.name=f|input|

I just started learning XPath and am trying to understand how to combine predicates with axes. Is it possible to do expressions like this with XPath? If so can someone knowledgeable please help?

Lactescent answered 2/2, 2010 at 1:45 Comment(0)
S
16

You could to do:

//input[@name='q' and ancestor-or-self::*[@name='f']]
// -- input element whose name='q' and who has an ancestor with the name='f'

or

//input[@name='q' and ../../../../../../*[@name='f']]
// -- input element whose name='q' and who is 5 parents up with the name='f'

You can use this desktop XPath Visualizer to test your XPath expressions. A basic tutorial can be found here.

Seasick answered 2/2, 2010 at 2:4 Comment(1)
nt related but got here try to find answer to my query if im correct this would have q as the node found? is there away to say i want f as the result. would like to say from y find z with contained text but give me y. aka y does contain the text somewhereForbade

© 2022 - 2024 — McMap. All rights reserved.