Click here to Skip to main content
15,896,727 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
    bool retval = false;
    XmlDocument doc = new XmlDocument();
    try
    {
        doc.Load(frmMain.FetchFileName(sFromFile));
        XmlNodeList nodes = doc.GetElementsByTagName("Type");
        foreach (XmlNode node in nodes)
        {
            if (node.FirstChild.InnerText == "Birthday")
            {
                //  Have found the right node. ? How do I delete it?
                //  node.RemoveChild(node.FirstChild);   Not like this
                //  doc.RemoveChild(node);               Nor like this
                //  node.RemoveChild(node);              Nor like this
                //  node.RemoveAll();                   // This gives no error
                node.ParentNode.RemoveChild(node);      // This gives no error

                doc.Save(sFromFile);
                retval = true;
                break;
            }

        }
    }
    catch
    {
        MessageBox.Show("Exception!!!", "Oops!");
        return false;
    }

    return retval;
}


What I have tried:

I have tried the code above, as you might see the first three attempts I made, failed.
Two attempts executed the code without complaining (commented This gives no error), but
did not actually delete anything from the file. Here is a snippet of the xml file.

The code looks for and finds the birthday node, which is what I am trying to delete
so that the file should look like this afterwards:
XML
<?xml version="1.0"?>
  <importanttype>
    <type>
      <name>Appointment
        <predefined>Yes
   .
   .       a bunch of other nodes in here
   .
    <type>
      <name>Holiday
      <predefined>Yes



I am baffled. Can anybody help me please?
Thanking you in anticipation, Noel.
Posted
Updated 25-Sep-18 8:54am
v2

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900