简体   繁体   中英

How to delete a node from a xml c#?

I have a xml structure like this:-

<Person id="1" Name="Rahul lamba" Manager_Id="13" Department="IT" />
<Person id="6" Name="Saurabh" Manager_Id="4" Department="IT" />
<Person id="5" Name="Amitesh" Manager_Id="6" Department="IT" />

Now I want to delete Manager_Id node from XML from every line.

I tried this but nothing works out

XmlNodeList l = doc.GetElementsByTagName("Person");

 foreach (XmlNode item in l)
     {
         foreach (var  item1 in item.ChildNodes)
             {
                 if (item1 == "Manager_Id")
                     {
                        //Code to remove Manager_Id node.
                     }
             }
      }

How can i achieve this?

Thanx in advance.

You can do it easily with Linq To Xml,

var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(filename)

xDoc.Descendants("Person")
    .Select(x => x.Attribute("Manager_Id"))
    .Where(x => x!=null)
    .ToList().ForEach(a => a.Remove());

var newxml = xDoc.ToString(); //xDoc.Save(fileName);
XmlTextReader reader = new XmlTextReader(@"C:\MyXml.xml");
        reader.Read();
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        XmlNode node = doc.SelectSingleNode("/Persons/Person[@Manager_Id=6]");
        node.ParentNode.RemoveChild(node);
        reader.Close();
        doc.Save(@"D:\MyXml.xml"); 

removing all nodes with att

XmlTextReader reader = new XmlTextReader(@"C:\MyXml.xml");
        reader.Read();
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        XmlNodeList lstNode = doc.SelectNodes("/Persons/Person[@Manager_Id]");
        foreach (XmlNode node in lstNode)
        {
            node.ParentNode.RemoveChild(node);
        }
        reader.Close();
        doc.Save(@"C:\MyXml.xml"); 

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