Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an xml element from file?

Tags:

c#

xml

.net-2.0

In an XML file such as :

<Snippets>
 <Snippet name="abc">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name="def">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>

How can I remove an element when only its attribute name (like abc or def) is given?

like image 536
rayanisran Avatar asked Dec 05 '11 08:12

rayanisran


2 Answers

You could try something like this:

string xmlInput = @"<Snippets>
 <Snippet name=""abc"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name=""def"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>";

// 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");
}
like image 162
marc_s Avatar answered Oct 06 '22 05:10

marc_s


XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Snippet")
    let attr = node.Attribute("name")
    where attr != null && attr.Value == "abc"
    select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

.Net 2.0

XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList nodes = doc.SelectNodes("//Snippet[@name='abc']");

Now you have the nodes whose attribute name='abc', you can now loop through it and delete

like image 29
FosterZ Avatar answered Oct 06 '22 05:10

FosterZ