1

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
1
  • As you're not simply removing items from the collection you're looping over, I'm not sure if "use a for loop" will work. Commented Aug 5, 2020 at 6:24

2 Answers 2

0

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.