C # linq delete multiple nodes

I am trying to remove several nodes in which a particular element(path) value contains a value, but I get a System.NullReferenceException any help that I am wrong in, I will be very grateful.

My xml looks like this:

 <?xml version="1.0" encoding="utf-8" standalone="yes"?> <ApplicationData Version="12.5.1" RootPath="FireFox-FILES"> <RegistrySystem> <DIR Operation="+" Path="C:\Temp\Microsoft\MediaPlayer\ShimInclusionList" /> <DIR Operation="+" Path="C:\Temp\MediaPlayer\ShimInclusionList\MM.EXE" /> <DIR Operation="+" Path="C:\Temp\MediaPlayer\ShimInclusionList\plugin-container.exe" /> <DIR Operation="+" Path="C:\Temp\Microsoft\MediaPlayer"> <ENTRY Name="" Value="43.0.4" Type="1" /> <ENTRY Name="CurrentVersion" Value="43.0.4 (x86 en-GB)" Type="1" /> </DIR> <DIR Operation="+" Path="C:\Program Files\Microsoft\MediaPlayer\ShimInclusionList\plugin-container.exe" /> <DIR Operation="+" Path="C:\Program Files\Microsoft\MediaPlayer\ShimInclusionList2\plugin.exe" /> <DIR Operation="+" Path="C:\Program Files\Microsoft\MediaPlayer\ShimInclusionList2\container.exe" /> <DIR Operation="+" Path="C:\Program Files\Microsoft\MediaPlayer\ShimInclusionList4"> <ENTRY Name="" Value="43.0.4" Type="1" /> <ENTRY Name="CurrentVersion" Value="43.0.4 (x86 en-GB)" Type="1" /> </DIR> </RegistrySystem> </ApplicationData> 

My code is as follows:

 XDocument xdoc = XDocument.Load(XmlFile); foreach (var node in xdoc.Descendants("DIR").Where(status => status.Attribute("Path").Value.Contains(@"C:\Temp\"))) { node.Remove(); } xdoc.Save(XmlFile); 

I am not sure where I am going wrong.

+5
source share
1 answer

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(); 
+6
source

Source: https://habr.com/ru/post/1244282/


All Articles