2

I am using HtmlAgilityPack to parse some data and writing statements like the below one to remove unwanted contents -

doc.DocumentNode.SelectNodes("//ul").ToList().ForEach(a => a.Remove());

This works well when there's <ul> element present in the HTML document. However, if there's no <ul> element, I get a Value cannot by null exception when converting it into .ToList().

I do not want to use the following -

doc.DocumentNode.SelectNodes("//ul")== null ? null : doc.DocumentNode.SelectNodes("//ul").ToList().ForEach(a => a.Remove());

What elegant alternatives do I have?

Nitesh
  • 2,022
  • 2
  • 41
  • 62
  • 1
    What do you find *inelegant* about your proposed solution? (Except, of course, that it wont compile! - `ForEach` is void and `null` on the other side won't coalesce) – Jamiec Oct 16 '15 at 09:25
  • @Jamiec, I know it won't compile and just wanted to share the way I don't want to write. This approach is OK when using on a single tag, but let's say I have around 100 tags and I want to remove them. lot of code to be written and I know I can transfer this into a function but that does not server the function properly as well. – Nitesh Oct 16 '15 at 09:33

4 Answers4

6

In your example you are calling doc.DocumentNode.SelectNodes("//ul") twice. What is wrong with

var nodes = doc.DocumentNode.SelectNodes("//ul");
if(nodes != null)
   nodes.ToList().ForEach(a => a.Remove());
Marius Bancila
  • 15,632
  • 8
  • 47
  • 86
4

If you have C# 6 available you can use The Null Conditional Operator:

doc.DocumentNode.SelectNodes("//ul")?.ToList().ForEach(a => a.Remove());

npinti
  • 51,070
  • 5
  • 71
  • 94
2

I would use RemoveAll instead of a ForEach (if you can use C#6):

doc.DocumentNode.SelectNodes("//ul")?.ToList().RemoveAll();

Or

var nodes = doc.DocumentNode.SelectNodes("//ul");
if(nodes != null)
    nodes.ToList().RemoveAll();
Thomas Ayoub
  • 28,235
  • 15
  • 95
  • 135
1

You need to check the null condition.

var docNodes = doc.DocumentNode.SelectNodes("//ul");
if(docNodes != null)
   docNodes .ToList().ForEach(a => a.Remove());
Galma88
  • 2,257
  • 6
  • 28
  • 47