Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xPath/HTML: Select node based on related node

Tags:

html

xpath

<html>
    <body>
        <table>
            <tr>
                <th>HeaderA</th>
                <th>HeaderB</th>
                <th>HeaderC</th>
                <th>HeaderD</th>
            </tr>
            <tr>
                <td>ContentA</td>
                <td>ContentB</td>
                <td>ContentC</td>
                <td>ContentD</td>
            </tr>
         </table>
    </body>
</html>

I am looking for the most efficient way to select the content 'td' node based on the heading in the corresponding 'th' node..

My current xPath expression..

/html/body/table/tr/td[count(/html/body/table/tr/th[text() = 'HeaderA']/preceding-sibling::*)+1]

Some questions..

  • Can you use relative paths (../..) inside count()?
  • What other options to find current node number td[?] or is count(/preceding-sibling::*)+1 the most efficient?
like image 648
chameleon95 Avatar asked Dec 28 '09 09:12

chameleon95


People also ask

Which XPath expression is used to match the current node?

The XPathNavigator class provides the Matches method to determine if a node matches an XPath expression. The Matches method takes an XPath expression as input and returns a Boolean that indicates if the current node matches the given XPath expression or the given compiled XPathExpression object.

What does node () do in XPath?

node() matches any node (the least specific node test of them all) text() matches text nodes only. comment() matches comment nodes. * matches any element node.

How do you select the second element with the same XPath?

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.

How do I combine two attributes in XPath?

The syntax for locating elements through XPath- Multiple Attribute can be written as: //<HTML tag>[@attribute_name1='attribute_value1'][@attribute_name2='attribute_value2]


1 Answers

  • It is possible to use relative paths inside count()
  • I have never heard of another way to find the node number...

Here is the code with relative xpath-code inside count()

/html/body/table/tr/td[count(../../tr/th[text()='HeaderC']/preceding-sibling::*)+1]

But well, it is not much shorter... It won't be shorter than this in my opinion:

//td[count(../..//th[text()='HeaderC']/preceding-sibling::*)+1]
like image 99
Harmen Avatar answered Oct 06 '22 10:10

Harmen