recently I have a question in this thread: Delete Attribute of Xml node c#
Again, I'm struggling with modifying the xml file.
Here's the xml:
<ApplicationConfiguration>
<ServerConfiguration>
<SecurityPolicies>
<ServerSecurityPolicy>
<SecurityMode>None_1</SecurityMode>
</ServerSecurityPolicy>
<ServerSecurityPolicy>
<SecurityMode>None_2</SecurityMode>
</ServerSecurityPolicy>
</SecurityPolicies>
</ServerConfiguration>
</ApplicationConfiguration>
What I want is to remove all ServerSecurityPolicy nodes, so the result will be:
<ApplicationConfiguration>
<ServerConfiguration>
<SecurityPolicies>
</SecurityPolicies>
</ServerConfiguration>
</ApplicationConfiguration>
Then I use this code:
string docaddress = "D:\\abc.xml";
XDocument doc = XDocument.Load(docaddress);
var root = doc.Root;
var these = root.Descendants().Where(p => p.Name.LocalName == "ServerSecurityPolicy");
foreach (var elem in these)
{
elem.Remove();
}
doc.Save(docaddress);
Here's the problem:
- When the code inside foreach is
elem.Remove(), it returns an error like: 'Object reference not set to an instance of an object' - When the code inside foreach is
label1.Text=elem.Name.LocalName, thelabel1displaysServerSecurityPolicy. So that theelem.Name.LocalNameworks normally, but theelem.Remove()does not? - I have tried
elem.RemoveNodes(). Based on the void description, I think the code will delete all child nodes (the SecurityMode nodes), but it doesn't work (no error, but just cannot delete anything). Same withelem.RemoveAll().
Can you tell me if I have done anything wrong? Thank you