Using System.Xml.XmlDocument for writing XML documents with C#

Posted: (EET/GMT+2)

 

In many small utilities and tools, I like to store configuration or simple data as XML. The System.Xml.XmlDocument class gives you a straightforward, HTML DOM style way to build XML documents in memory and write them to disk.

Here's a small example of how to create a basic XML file:

XmlDocument doc = new XmlDocument();

XmlElement root = doc.CreateElement("settings");
doc.AppendChild(root);

XmlElement user = doc.CreateElement("user");
user.InnerText = "admin";
root.AppendChild(user);

XmlElement lastRun = doc.CreateElement("lastRun");
lastRun.InnerText = DateTime.Now.ToString();
root.AppendChild(lastRun);

doc.Save("Settings.xml");

This creates a document like this:

<settings>
  <user>admin</user>
  <lastRun>...</lastRun>
</settings>

The API is quite easy to understand: create elements, set their inner text or attributes, attach them to the parent, and then call Save().

For reading data back, SelectSingleNode() is handy:

XmlDocument doc = new XmlDocument();
doc.Load("Settings.xml");

string user = doc.SelectSingleNode("/settings/user").InnerText;

This is simple and effective. Happy hacking!