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,286
  • 2
  • 43
  • 65
  • 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
  • 16,053
  • 9
  • 49
  • 91
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,780
  • 5
  • 72
  • 96
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
  • 29,063
  • 15
  • 95
  • 142
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,398
  • 6
  • 29
  • 50