简体   繁体   中英

Remove Element from xml file with c#

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 , the label1 displays ServerSecurityPolicy . So that the elem.Name.LocalName works normally, but the elem.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 with elem.RemoveAll() .
    Can you tell me if I have done anything wrong? Thank you

it's me again. I have solve it by replace the line
var these = root.Descendants().Where(p => p.Name.LocalName == "ServerSecurityPolicy");
with
var 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM