.NET, C#, Programming Tutorial

C# Tutorial – XmlWriter

XmlTextWriter renders XML data to a string. This string remains in the memory of the C# program. We use an underlying buffer—in this case, a StringWriter instance. XmlTextWriter is useful for in-memory generation of XML.

OK, suppose that we want to write to file some data and the XML file will be like below:

<?xml version="1.0" encoding="utf-8"?>
<Classes>
  <NumOfClasses>3</NumOfClasses>
  <Class>
    <NumOfStudents>3</NumOfStudents>
    <Student>
      <Name>John</Name>
      <Age>19</Age>
      <Gender>Male</Gender>
      <Name>US</Name>
    </Student>
    <Student>
      <Name>Mary</Name>
      <Age>18</Age>
      <Gender>Female</Gender>
      <Name>UK</Name>
    </Student>
    <Student>
      <Name>Hung</Name>
      <Age>20</Age>
      <Gender>Male</Gender>
      <Name>VN</Name>
    </Student>
  </Class>
  <Class>
    <NumOfStudents>4</NumOfStudents>
    <Student>
      <Name>Peter</Name>
      <Age>21</Age>
      <Gender>Male</Gender>
      <Name>US</Name>
    </Student>
    <Student>
      <Name>Maria</Name>
      <Age>27</Age>
      <Gender>Female</Gender>
      <Name>UK</Name>
    </Student>
    <Student>
      <Name>Thai</Name>
      <Age>25</Age>
      <Gender>Male</Gender>
      <Name>VN</Name>
    </Student>
    <Student>
      <Name>Bao</Name>
      <Age>23</Age>
      <Gender>Male</Gender>
      <Name>VN</Name>
    </Student>
  </Class>
  <Class>
    <NumOfStudents>3</NumOfStudents>
    <Student>
      <Name>Bill</Name>
      <Age>22</Age>
      <Gender>Male</Gender>
      <Name>US</Name>
    </Student>
    <Student>
      <Name>Nguyen</Name>
      <Age>23</Age>
      <Gender>Female</Gender>
      <Name>UK</Name>
    </Student>
    <Student>
      <Name>Mark</Name>
      <Age>25</Age>
      <Gender>Male</Gender>
      <Name>VN</Name>
    </Student>
  </Class>
</Classes>

Now, let’s start by create a new C# Console project and create some Model class to hold data for writing
Student.cs

enum Gender
{
	Male,
	Female
}

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Gender Gender { get; set; }
    public string Address { get; set; }

    public Student(string newName, int newAge, Gender newGender, string newAddress)
    {
        Name = newName;
        Age = newAge;
        Gender = newGender;
        Address = newAddress;
    }
}

Class.cs

class Class
{
    public string Name { get; set; }
    public int NumOfStudents { get; set; }
    public List Students { get; set; }

    public Class()
    {

    }

    public Class(string newName, int newNumOfStudents, List newListStudents)
    {
        Name = newName;
        NumOfStudents = newNumOfStudents;
        Students = newListStudents;
    }
}

And this is the entire code to perform writing data to XML file

using System.Collections.Generic;
using System.Xml;

namespace XmlTest
{
	internal class Program
	{
		private static void Main()
		{
			//
			// Create models
			//
			var listClasses = new List
								  {
									  new Class("ItClass", 3,
												new List
													{
														new Student("John", 19, Gender.Male, "US"),
														new Student("Mary", 18, Gender.Female, "UK"),
														new Student("Hung", 20, Gender.Male, "VN")
													}),
									  new Class("AdClass", 4,
												new List
													{
														new Student("Peter", 21, Gender.Male, "US"),
														new Student("Maria", 27, Gender.Female, "UK"),
														new Student("Thai", 25, Gender.Male, "VN"),
														new Student("Bao", 23, Gender.Male, "VN")
													}),
									  new Class("MathClass", 3,
												new List
													{
														new Student("Bill", 22, Gender.Male, "US"),
														new Student("Nguyen", 23, Gender.Female, "UK"),
														new Student("Mark", 25, Gender.Male, "VN")
													})
								  };

			// Auto indent mode for XML file
			var settings = new XmlWriterSettings {Indent = true};

			//
			// Create a XML file for writing
			//
			using (var writer = XmlWriter.Create("Classes.xml", settings))
			{
				writer.WriteStartDocument(); // Write XML declaration

				writer.WriteStartElement("Classes"); // &lt;-- Write the Classes element.

				writer.WriteElementString(&quot;NumOfClasses&quot;,
										  listClasses.Count.ToString());
					// Write NumOfClasses attribute of Classes element

				foreach (var c in listClasses)
				{
					writer.WriteStartElement(&quot;Class&quot;); // &lt;-- Write the Class element.

					writer.WriteElementString(&quot;NumOfStudents&quot;,
											  c.NumOfStudents.ToString());
						// Write NumOfStudents attribute of Class element

					foreach (var s in c.Students)
					{
						writer.WriteStartElement(&quot;Student&quot;); // &lt;-- Write the Student element.

						writer.WriteElementString(&quot;Name&quot;, s.Name);
						writer.WriteElementString(&quot;Age&quot;, s.Age.ToString());
						writer.WriteElementString(&quot;Gender&quot;, s.Gender == Gender.Male ? &quot;Male&quot; : &quot;Female&quot;);
						writer.WriteElementString(&quot;Name&quot;, s.Address);

						writer.WriteEndElement(); // &lt;-- Close Student element.
					}

					writer.WriteEndElement(); // &lt;-- Close Class element.
				}

				writer.WriteEndElement(); // &lt;-- Close Classes element.

				writer.WriteEndDocument(); // Closes any open elements or attributes and
				// puts the writer back in the Start state.
			}
		}
	}
}

I’m going to have some explanation for above code
using statement:

using (XmlWriter writer = XmlWriter.Create("Class.xml"))
{
	// Write data to XML file by write object
}

We use using keyword in this statement to ensure when we leave this block, the XmlWriter object will be automatically released. Otherwise, we must to call Dispose method manually but we will lose system resources when exceptions are thrown.

Write XML declaration

using (XmlWriter writer = XmlWriter.Create("Class.xml"))
{
	writer.WriteStartDocument();
	// ...
	writer.WriteEndDocument();
}

Writes out the XML declaration with the version “1.0”. The encoding attribute is determined by the implementation of IXmlWriterOutput. By default, the encoding is UTF-8.

Write an element to file

using (XmlWriter writer = XmlWriter.Create("Class.xml"))
{
	writer.WriteStartDocument();
	writer.WriteStartElement("Classes");	// &lt;-- Write the Classes element.
	// ... Write all attributes, childnodes of Classes element here
	writer.WriteEndElement();				// &lt;-- Closes Classes element
	writer.WriteEndDocument();
}

We write an element to file by WriteStartElement(string elementName) and close it by WriteEndElement().

Write attribute, child-nodes of within an element

using (XmlWriter writer = XmlWriter.Create("Class.xml"))
{
	writer.WriteStartDocument();
	writer.WriteStartElement("Classes");	// &lt;-- Write the Classes element.
	writer.WriteElementString(&quot;NumOfClasses&quot;, listClasses.Count);	// Write NumOfClasses attribute of Classes element		foreach(var c in listClasses)
	{
		writer.WriteStartElement(&quot;Class&quot;);	// &lt;-- Write the Class element.
		writer.WriteElementString(&quot;Name&quot;, c.Name);	// Write Name attribute of Class element
		writer.WriteElementString(&quot;NumOfStudents&quot;, c.NumOfStudents);	// Write NumOfStudents attribute of Class element
		foreach(var s in listStudents)
		{
			// ... Write all student element here
		}
		writer.WriteEndElement();			// &lt;-- Closes Classes element
	}
	writer.WriteEndElement();				// &lt;-- Closes Class element
	writer.WriteEndDocument();
}

OK. So far, we have understood how to create a XML file, write XML declaration, write XML element and its attribute as well as its child nodes.

Note:
If we use the using block as bellow, we don’t need call the Close method explicitly because, when the XmlWriter object be out off the using block, the Dispose method of it will be implicitly called. Otherwise, we must explicitly call the Close method.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s