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
2
3
4
5
6
<root>
  <node>
    <item1 attribute="abc123">text</item1>
    <item2 />
  </node>
</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:

1
using System.Xml.Linq;

To write an xml file you do:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
XDocument doc = new XDocument
                (
                    new XElement("root",
                        new XElement("node",
                            new XElement("item1", new XAttribute("attribute", "abc123"), "text"),
                            new XElement("item2")
                            )
                        )
                );
doc.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
2
3
4
5
6
//load the file
XDocument doc = XDocument.Load("doc.xml");
// this will print the element value 
Console.WriteLine(doc.Element("root").Element("node").Element("Item1").Value);
// this will print its attribute value
Console.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