I'm not sure why you get the exception, but I strongly suspect because you are modifying the document during the request.
If you change your code to use the ToList()
call to get a list of nodes to delete that don't throw:
foreach (var node in xdoc.Descendants("DIR") .Where(status => status.Attribute("Path").Value.Contains(@"C:\Temp\")) .ToList()) { node.Remove(); }
However, this is not the best way. A better approach is to use the Remove(this IEnumerable<XElement>)
extension method Remove(this IEnumerable<XElement>)
:
xdoc.Descendants("DIR") .Where(status => status.Attribute("Path").Value.Contains(@"C:\Temp\")) .Remove();
No need for foreach
. Now, to make it reliable in the form of DIR
elements without the Path
attribute, you can use the string instead:
xdoc.Descendants("DIR") .Where(status => ((string) status.Attribute("Path") ?? "").Contains(@"C:\Temp\")) .Remove();
source share