Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete node from XML file using C# [duplicate]

Tags:

Possible Duplicate:
How to remove an XmlNode from XmlNodeList

Hi, How can i delete a set of nodes from an XML file.? Here is a code snippet.

string path = @"C:\Documents and Settings\e454935\Desktop\NUnitSettings.xml"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.Load(fs); fs.Close(); xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]); FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite); xmldoc.Save(WRITER); WRITER.Close();  

I tried the following code simply to delete a node and got "Object reference not set to an instance of an object." at

xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]); 

Here is a sample XML file,

<?xml version="1.0"?> <Xml1>   <Settings>     <Setting name="DisplayFormat" value="Full" />     <Setting name="File1" value="a" />     <Setting name="File1" value="b" />     <Setting name="File1" value="c" />     <Setting name="File1" value="d" />   </Settings> </Xml1> 

Actually from this file i want to delete the Four File1 nodes which has the values "a,b,c,d" and then i want to add a node,

<Setting name="File1" value="e" /> 

How can i do this.?

like image 838
SyncMaster Avatar asked May 28 '09 07:05

SyncMaster


People also ask

How to delete a child node in xml using c#?

node. ParentNode. RemoveChild(node); that is all you need, the node including any children is removed.

How do I clear an XML file?

In the XML Files explorer, right-click the XML file or XML element that you want to remove and click Delete.

What is XML and node in XML?

Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.


1 Answers

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml"); var q = from node in doc.Descendants("Setting")         let attr = node.Attribute("name")         where attr != null && attr.Value == "File1"         select node; q.ToList().ForEach(x => x.Remove()); doc.Save("output.xml"); 
like image 113
idursun Avatar answered Sep 28 '22 08:09

idursun