XPath partial of attribute known

avaleske picture avaleske · May 14, 2009 · Viewed 28.7k times · Source

I know the partial value of an attribute in a document, but not the whole thing. Is there a character I can use to represent any value? For example, a value of a label for an input is "A. Choice 1". I know it says "Choice 1", but not whether it will say "A. " or "B. " before the "Choice 1". Below is the relevant HTML. There are other attributes for the input and the label, but they are not the same every time the page is rendered, so I can't use them as references:

<tr>
<td><input type="checkbox" /><label>A. Choice 1</label></td>
</tr><tr>
    <td><input type="checkbox" /><label>B. Choice 2</label></td>
</tr><tr>
<td><input type="checkbox" /><label>C. Choice 3</label></td>
</tr><tr>
     <td><input type="checkbox" /><label>D. Choice 4</label></td>
</tr>

This is the XPath expression I'm using to select the input next to the label with the value of "Choice 1", except that the A is in front of it in the HTML:

//td[label="Choice 1"]/input

I don't know if the A in the HTML will be an A, B, or C, etc. But I do know that the correct input will always have the Choice 1 text next to it. How do I say to select it if the label contains Choice 1, as opposed to being equal to choice 1?

Answer

Ronald Wildenberg picture Ronald Wildenberg · May 14, 2009

Your XPath expression should look like this:

//td[contains(@label, 'Choice 1')]/input

You select all td elements that have a label that contains Choice 1 and then you select the input elements inside these td elements.

EDIT: Tomalak's comment correctly suggests an improvement to prevent a match against 'Choice 11' (or 'Choice 12345', ...).