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:
elem.Remove()
, it returns an error like: 'Object reference not set to an instance of an object'label1.Text=elem.Name.LocalName
, the label1
displays ServerSecurityPolicy
. So that the elem.Name.LocalName
works normally, but the elem.Remove()
does not?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 with elem.RemoveAll()
.it's me again. I have solve it by replace the linevar these = root.Descendants().Where(p => p.Name.LocalName == "ServerSecurityPolicy");
withvar these = root.Descendants("SecurityPolicies");
then RemoveAll()
This code will help to get your expected output
public static void Main(string[] args)
{
string xmlpath = "sample.xml";
XDocument xdoc = XDocument.Load(xmlpath);
var list = xdoc.Elements().Descendants().ToList();
foreach (var item in list)
{
item.Descendants("ServerSecurityPolicy").Remove();
}
xdoc.Save(xmlpath);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.