Modify XML File C# with Example
To modify an XML ﬁle with XDocument, you load the ﬁle into a variable of type XDocument, modify it in memory, then
save it, overwriting the original ﬁle. A common mistake is to modify the XML in memory and expect the ﬁle on disk
Given an XML ﬁle:
You want to modify the Banana's color to brown:
1. We need to know the path to the ﬁle on disk.
2. One overload of XDocument.Load receives a URI (ﬁle path).
3. Since the xml ﬁle uses a namespace, we must query with the namespace AND element name.
4. A Linq query utilizing C# 6 syntax to accommodate for the possibility of null values. Every . used in this query
has the potential to return a null set if the condition ﬁnds no elements. Before C# 6 you would do this in
multiple steps, checking for null along the way. The result is the element that contains the Banana.
Actually an IEnumerable, which is why the next step uses FirstOfDefault().
5. Now we extract the FruitColor element out of the Fruit element we just found. Here we assume there is just
one, or we only care about the ﬁrst one.
6. If it is not null, we set the FruitColor to "Brown".
7. Finally, we save the XDocument, overwriting the original ﬁle on disk.
string xmlFilePath = "c:\\users\\public\\fruit.xml";
XDocument xdoc = XDocument.Load(xmlFilePath);
XNamespace ns = "http://www.fruitauthority.fake";
var elBanana = xdoc.Descendants()?.
Elements(ns + "FruitName")?.
Where(x => x.Value == "Banana")?.
Ancestors(ns + "Fruit");
var elColor = elBanana.Elements(ns + "FruitColor").FirstOrDefault();
if (elColor != null)
elColor.Value = "Brown";
The ﬁle now looks like this:
C# 7.0 is the seventh version of C#. This version contains some new features: language support for Tuples, local
functions, out var declarations, digit separators, binary literals, pattern matching, throw expressions, ref return
and ref local and extended expression bodied members list.
Oﬃcial reference: What's new in C# 7