Thursday, May 20, 2010

Writing XML in C# .NET with XmlTextWriter

A few days ago I started writing application that will write and read settings that are saved in XML file.

So, considering that I have never done this in C# (i’m fairly new to it), I’ve read some documentation and came to the conclusion that XmlTextWriter will be the best for the job. Am I wrong? I could use XmlDocument but since I don’t need to do anything more then simply write XML, I see no reason for using it.

So let’s get dirty. :)


First, add the required reference when working with XML in C#.

using System.Xml;

Now we need to create a new XmlTextWriter instance.

XmlTextWriter writer = new XmlTextWriter("data.xml", null);

data.xml will be the name of the file that will be created, in this case in the same folder as the exe itself.

null means that the default encoding will be used which is UTF-8.

Now we are going to set the indenting.

writer.Formatting = Formatting.Indented;

Now, let’s get to the actual XML elements. First, we need to add declaration to the XML.

writer.WriteStartDocument();

Which will output this:

<?xml version="1.0"?>

Then it is time to add the root element to the XML.

writer.WriteStartElement("users");

After root, we will add a node called profile with an attribute called id that has the value of 10.

Read more: lessthanweb

Posted via email from jasper22's posterous