XPath: How to select elements based on their value

xpath

I am new to using XPath and this may be a basic question. Kindly bear with me and help me in resolving the issue. I have an XML file like this:

<RootNode>
  <FirstChild>
    <Element attribute1="abc" attribute2="xyz">Data</Element>
  <FirstChild>
</RootNode>

I can validate the presence of an <Element> tag with:

//Element[@attribute1="abc" and @attribute2="xyz"]

Now I also want to check the value of the tag for string "Data". For achieving this I was told to use:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

When I use the later expression I get the following error:

Assertion failure message: No Nodes Matched //Element[@attribute1="abc" and @attribute2="xyz" and Data]

Kindly provide me with your advice whether the XPath expression I have used is valid. If not what will be the valid XPath expression?

Best Answer

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
Related Topic