views:

248

answers:

1

Hey everyone,

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?

+3  A: 

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.

Rubens Farias
Thank you so much for your fast and clarifying response. I may have more questions later.
gtaborga