-2

I have a HTML file that looks like this:

<div class="user_meals">
<div class="name">Name Surname</div>
<div class="day_meals">
    <div class="meal">First Meal</div>
</div>  
<div class="day_meals">
    <div class="meal">Second Meal</div>
</div>
<div class="day_meals">

    <div class="meal">Third Meal</div>

</div>
<div class="day_meals">

    <div class="meal">Fourth Meal</div>

</div>

<div class="day_meals">

    <div class="meal">Fifth Meal</div>

</div>

This code repeats a few times.

I want to get Name and Surname which is between <div> tag with class "name".

This is my code using HtmlAgilityPack:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"C:\workspace\file.html");

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='name']"))
{
    string vaule = node.InnerText;
}

But actually it doesn't work. Visual Studio throws me Exception:

An unhandled exception of type 'System.NullReferenceException'.

Moses Davidowitz
  • 982
  • 11
  • 28
bugZ
  • 466
  • 5
  • 19

1 Answers1

1

You are using wrong method to load HTML from a path LoadHtml expect HTML and not location of the file. Use Load instead.

The error you are getting is quite misleading as all properties are not null and standard tips from What is a NullReferenceException, and how do I fix it? don't apply.

Essentially this comes from the fact SelectNodes correctly returns null as there are not elements matching the query and foreach throws on it.

Fixed code:

HtmlDocument doc = new HtmlDocument();
// either doc.Load(@"C:\workspace\file.html") or pass HTML:
doc.LoadHtml("<div class='user_meals'><div class='name'>Name Surname</div></div> ");
var nodes = doc.DocumentNode.SelectNodes("//div[@class='name']");
// SelectNodes returns null if nothing found - may need to check 
if (nodes == null)
{ 
    throw new InvalidOperationException("Where all my nodes???");    
}
foreach (HtmlNode node in nodes)
{
    string vaule = node.InnerText;
    vaule.Dump();
}
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179