XmlWriter writes XML data from objects in memory. XML files are excellent for interoperability with other systems and Internet sites. We use XmlWriter in a C# program. We review each step required.

Example. First, we see the finished code from this tutorial. You can see that there is an Employee class, which contains four fields, four public getters, and a constructor. All the fields are private, not public.

Also: The class is properly encapsulated and has exclusive control over its internal fields.

In this program, we instantiate an array of four Employee instances. The constructor from the Employee class is used, and four employee items are assigned to the array slots, specifying the ID, first name, last name, and salary figure.

Keyword using. I would like to emphasize that the using-statement here, which wraps all the XmlWriter code, is important to remember. What the using statement does is ensure that the system resources are always released.

Caution: If you manually call Dispose, you will lose system resources when exceptions are thrown.

So: The using keyword here basically is a shorthand for the finally statement. This does not require an exception to take effect.

Write root. Next, we need to add a root element to the XML. It is important to add a root element with XmlWriter that contains all the other elements. There can be only one root element and it can have any name.

Info: If you don't create the root element, you get a perplexing exception. Please see the exception below.

Write array. Next, we can loop through the elements in our Employee array. The array we use here is shown in full in the first block of code above. The foreach-loop is used because we don't need any special indexing.

Note: The WriteStartElement method begins a new block, which is empty. It contains no data.

Write object. Here we take the values from each Employee object in the array and access the property getters. These getters complicate the code, but provide a much safer system where data integrity is more likely to be preserved.

Here: The four fields from the Employee object are inserted into special tags in the XML.

Problem. When attempting to use XmlWriter over the years, I have often encountered this InvalidOperationException. The problem here is that you always have to put the root element into your document.

System.InvalidOperationException:
Token StartElement in state EndRoot Element would result in an invalid XML document.
Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or
ConformanceLevel.Auto if you want to write an XML fragment.

Options. We have barely scratched the surface of XmlWriter so far. For completeness, I present my notes on the class. There are many more options that I do not describe—many classes are complex in the .NET Framework.

XmlWriterSettings: This is an object that you can pass to the XmlWriter.Create method to specify various options of how XmlWriter operates.

XmlWriter.Create: This is a static method that returns a new XmlWriter. It is important that you wrap this in a using-statement.

CheckedCharacters: This performs character-level validation of the XML you are writing. This can ensure correctness.

IndentChars, NewLine: These options let you specify how the resulting XML is formatted. They are straightforward and described on MSDN.

Output. We see that there are four employee elements with four sub-elements in each. It does not have attributes on the elements, but is a properly-formed document. The XML could be used as a data file for an application.

Note: The screenshot shows XML Notepad, which is a program available from Microsoft.

Dispose. Is it necessary to call the Close method on an XmlWriter? If you use the using-statement on an XmlWriter, the Dispose method will be called. In the Dispose method, we see that the Close method is called.

So: You do not need to call Close if you use using. Otherwise you should call Close explicitly.

XmlReader. This article is focused on writing XML, not reading it. However, the two procedures have a lot in common, and a companion article is available. The XmlReader article has a slightly different focus It is ordered in a clearer way.

Summary. This tutorial used XmlWriter. It covered how you can use the using-statement. And it invoked several methods on the type. We looked at some common pitfalls, and checked XML Notepad and the output XML.