Read and write xml files

In this tutorial we’re going to find how to read and write xml files in c#.

Prerequisite

XML file format

XML files can be used to store data, they replace the old ini files.
XML have a structure like this one:

1<root>
2  <node>
3    <item1 attribute="abc123">text</item1>
4    <item2 />
5  </node>
6</root>

These file are made of nodes, each node can contain more nodes inside, and each of them may have attributes.
In the example before, root, node, item1 and item2 are nodes, only the node item1 has an attribute set to “abc123” as value.
The node item2 is an empty node.

Write XML

Before start add this on top of your code:

1using System.Xml.Linq;

To write an xml file you do:

 1XDocument doc = new XDocument
 2                (
 3                    new XElement("root",
 4                        new XElement("node",
 5                            new XElement("item1", new XAttribute("attribute", "abc123"), "text"),
 6                            new XElement("item2")
 7                            )
 8                        )
 9                );
10doc.Save("doc.xml");

This code will create a file with the same content you saw before.
new XElement(name) create a new element, if you don’t put other arguments other than the name, it will create an empty element(like the item2).
As arguments you can put the content of the element(just write a string) or you can create a new element to make nested nodes.
new XAttribute(propriety, value) let you create an attribute to the element.
doc.Save(file name) This function just save the file.
As you see it’s very easy to create a xml file, to read it it’s even easier.

Read XML

To read data from xml file you do:

1//load the file
2XDocument doc = XDocument.Load("doc.xml");
3// this will print the element value 
4Console.WriteLine(doc.Element("root").Element("node").Element("Item1").Value);
5// this will print its attribute value
6Console.WriteLine(doc.Element("root").Element("node").Element("Item1").Attribute("attribute").Value);

Conclusion

I hope you found this quick tutorial useful 😄
As always, let me know on Twitter if you liked it! @CodeSailer