Search code examples
c#html-agility-pack

Get the second node with same class


I`m having some trouble parsing some nodes with HtmlAgilityPack.

Here is the problem:

I have many nodes with the class "test", but i want to selct the second one.

If I make something like this:

html.DocumentNode.SelectSingleNode ("//font[@class='test' and position()=1]")

It returns the value that I expected... but if I try to get the second one it returns null... but the question is.. why?

html.DocumentNode.SelectSingleNode ("//font[@class='test' and position()=2]")

This line of code brings me all of them, and i'm really confuse now, because using position()=1 the lib had to return only the first one, right?

html.DocumentNode.SelectNodes ("//font[@class='test' and position()=1]")

Thanks guys!


Solution

  • The correct code would be

    html.DocumentNode.SelectSingleNode ("(//font[@class='test'])[2]")
    

    The code you used selects the first or second test element within its parent element, not the first or second element in the sequence of all font elements of class test.