1

Currently I am dealing with an HtmlDocument in c# from a website:

return doc.DocumentNode.SelectSingleNode("//span[@title=input]").InnerText;

I want to get the inner text from a span with the title "input". Above is my current code but I receive a NullReferenceException when trying to run it. What should my implicit parameter be in order to retrieve the text from "input"?

Cameron Barge
  • 309
  • 2
  • 6
  • 17

3 Answers3

2

You have to delimit strings with quotes in XPath expressions:

return doc.DocumentNode.SelectSingleNode("//span[@title='input']").InnerText;

Plain input will try to match a node by that name and substitute its value.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • After changing my code to: return doc.DocumentNode.SelectSingleNode(".//span[@title='input']").InnerText; I still received the same error. – Cameron Barge Oct 24 '12 at 19:16
  • You can look at my full code for my program here: http://stackoverflow.com/questions/13031757/nullreferenceexception-with-htmldocument-reference-in-c-sharp – Cameron Barge Oct 24 '12 at 19:17
  • @Cameron, well, that means there is no `` element whose `title` attribute is equal to the string `'input'` in your document. *(Update: I just noticed your `.` token before `//`, that's not the same thing, in that case it means there is no matching `` element under the current one.)* – Frédéric Hamidi Oct 24 '12 at 19:17
  • I fixed it my doing ("//span[@title='"+input+"']") The reason is that input is not a string, and therefore needs to be concatenated. Thanks for all your help! – Cameron Barge Oct 25 '12 at 18:48
0

Make sure the span element with title attribute exists with value as 'input' in your HtmlDocument object of HtmlAgilityPack.

For proper checking, try this piece of code:

if (doc.DocumentNode != null)
{
    var span = doc.DocumentNode.SelectSingleNode("//span[@title='input']");

    if (span != null)
        return span.InnerText;
}
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
-1
return doc.DocumentNode.SelectSingleNode("//span[@title='"+input+"']").InnerText;

Because input is not a string, it has to be concatenated to fit the parameters. Thanks for all of you help!

Cameron Barge
  • 309
  • 2
  • 6
  • 17