Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test current node with XPath

Tags:

c#

.net

xml

xpath

.NET's XPath functions offer the usual features like SelectSingleNode and SelectNodes. They can only find child nodes specified by an XPath query.

But what if I want to test the current node whether it matches a given XPath specification? How does that work?

Let's say I have an HTML document where I have found a table node.

<table>
  <tr>
    <td>...</td>
  <tr>
  <tr class="abc">
    <td>...</td>
  </tr>
</table>

I can find all tr elements from there. Once I've reached a tr element (I could also get there through navigation, not XPath), I'd like to know whether it matches certain criteria. These are best specified as an XPath string.

This is what I'm looking for:

XmlNode trNode = ...;
bool result = trNode.Matches("tr[@class='abc']");

Is this supported by .NET's (very limited) XPath functionality? Or, if that makes a difference, the HtmlAgilityPack package?

like image 739
ygoe Avatar asked Feb 25 '26 06:02

ygoe


1 Answers

[...] what if I want to test the current node whether it matches a given XPath specification?

You can check that with the self:: axis.
So if your current node is tr and you want to check if the current tr element is one with a class attribute with the value abc, use the following XPath expression:

self::tr[@class='abc']

I guess that this is what you want, isn't it?

like image 81
zx485 Avatar answered Feb 26 '26 20:02

zx485



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!