Eugene
Eugene

Reputation: 5553

Xpath: detecting existence of the node with specific data

Here are two excerpts of my xml.

Excerpt I:

<tr>
    <td>
        <label>Attribute Name</label>
    </td>
    <td>
        <input>
        <div class="formCellError">Error message</div>
    </td>
</tr>

Excerpt II:

<tr>
    <td>
        <span>
            <b>
                <label>Attribute Name</label>
            </b>
        </span>
        <input>
        <div class="formCellError">Error message</div>
    </td>
</tr>

As you can see, the structure of theese nodes differs. In the 1st excerpt <label> and <div> are inside the same <td> tag, whilst in the 2nd excerpt <label> and <div> are inside different <td> tags.

I need to test, that there is a node with error message in the same <td> node, or at least in the preceding sibling <td> node. The <td> node is specified by the label

Do you have an idea, how to detect existence of nodes with the single X-path expression? I've designed a solution, which is retrieving <tr> tag and then analyze it, but it too complicated to support and quite slow.

Upvotes: 0

Views: 105

Answers (3)

Eugene
Eugene

Reputation: 5553

The following XPath expression detects specific error situated next to specific attribute. Work nice for Excerpt I and Excerpt II

//tr[//label/text()='Attribute Name' and //div[@class='formCellError' and text()='Error message'] ]

Upvotes: 0

Jens Erat
Jens Erat

Reputation: 38732

Looking at the examples, you're not looking for errors in the first preceding sibling, but following sibling. If not, modify the query to use the preceding-sibling axis step instead.

You might have to remove the (: comments :) before being able to run; I used the XQuery comment syntax for explaining the query.

//td                                  (: find table cells :)
  [.//label]                          (: having a label in it :)
  [
    .//div[@class='formCellError']    (: and an error in the same cell :)
      or
    following-sibling::td[1]//div[@class='formCellError'] (: the following cell :)
  ]

Upvotes: 1

Jerry
Jerry

Reputation: 46

if you're asking how you can find all the TR nodes that contain a DIV with the class of "formCellError" then you can do that with this XPath:

//tr[.//div[@class='formCellError']]

If you're asking how to find all Labels that are in a TR that contains a DIV with the class of "formCellError" then use this XPath:

//tr[.//div[@class='formCellError']]//label

Upvotes: 0

Related Questions