| Modify XML File To modify an XML file with XDocument, you load the file into a variable of type XDocument, modify it in memory, then save it, overwriting the original file.
A common mistake is to modify the XML in memory and expect the file on disk to change. Given an XML file: You want to modify the Banana's color to brown: - We need to know the path to the file on disk.
- One overload of
XDocument.Load receives a URI (file path). - Since the xml file uses a namespace, we must query with the namespace AND element name.
- 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 finds no elements. Before C# 6 you would do this in multiple steps, checking for null along the way. The result is the <Fruit> element that contains the Banana. Actually an IEnumerable<XElement>, which is why the next step uses FirstOfDefault(). - 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 first one.
- If it is not null, we set the FruitColor to "Brown".
- Finally, we save the
XDocument, overwriting the original file on disk. The file now looks like this: |