How to remove an xml element from file?

后端 未结 3 477
攒了一身酷
攒了一身酷 2020-11-29 12:01

In an XML file such as :


 
   
   code goes here
   
 

          


        
3条回答
  •  鱼传尺愫
    2020-11-29 12:50

    You could try something like this:

    string xmlInput = @"
     
       
       code goes here
       
     
    
     
       
       code goes here
       
     
    ";
    
    // create the XML, load the contents
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlInput);
    
    // find a node - here the one with name='abc'
    XmlNode node = doc.SelectSingleNode("/Snippets/Snippet[@name='abc']");
    
    // if found....
    if (node != null)
    {
       // get its parent node
       XmlNode parent = node.ParentNode;
    
       // remove the child node
       parent.RemoveChild(node);
    
       // verify the new XML structure
       string newXML = doc.OuterXml;
    
       // save to file or whatever....
       doc.Save(@"C:\temp\new.xml");
    }
    

提交回复
热议问题