Your error means that some of div
elements do not have id
attribute. Thus s.Attribute("id")
returns null
. Trying to get it's value throws exception. If you will cast attribute to string
instead of trying to access it's Value
, you will not get error (null
will be returned if attribute was not found):
xDoc.Descendants("div")
.Where(d => (string)d.Attribute("id") == "item" + item)
.Remove();
Also thus you are dealing with HTML I suggest you to use appropriate tool - HtmlAgilityPack. Removing your div nodes will look like:
HtmlDocument doc = new HtmlDocument();
doc.Load(path_to_file);
foreach (var div in doc.DocumentNode.SelectNodes("//div[@id='item456']"))
div.Remove();