C# – How to delete node from XML file using C#


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();
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);

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


Here is a sample XML file,

<?xml version="1.0"?>
    <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" />

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.?

Best Solution

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());