C# XmlTextWriter Tutorial and Example
In this tutorial, we want to see how to programmatically create an XML file programmatically. The magic ball we use is the XmlTextWriter
, a class defined in the System.Xml
namespace.
Let's start.
What is XmlTextWriter
Well it's a class defined in the System.Xml
namespace that will provide us with a fast, non-cached, forward-only way of generating streams or files containing XML data.
You instantiate the XMLTextWriter with the TextWriter
to write to as well as the encoding to use. You can also indent the Xml for readability:
var xmlTextWriter = new XmlTextWriter("products.xml", Encoding.UTF8) {Formatting = Formatting.Indented};
(a). Starting XML Document
To write the start tag we use the WriteStartDocument()
method of the XmlTextWriter
class.
xmlTextWriter.WriteStartDocument();
Later we will close it this way:
xmlTextWriter.WriteEndDocument();
(b). Writing XML Comment
To programmatically write an xml comment you use the WriteComment()
method of the XmlTextWriter
class:
xmlTextWriter.WriteComment("XML Document Commnet");
(c). Writing XML Comment
To programmatically write the start element:
xmlTextWriter.WriteStartElement("PRODUCT");
(d). Writing XML Element String
You use the WriteElementString()
method:
xmlTextWriter.WriteElementString("NAME", "HP ELITEBOOK");
Here's how we will close it:
xmlTextWriter.WriteEndElement();
Video Tutorial
Here's a video tutorial:
Example - Create XML File Programmatically
In this example we will see how to programmatically create an xml file with valid xml data using the XmlTextWriter
class. We create that Xml file in the /bin/debug
folder of the project.
Program.cs
using System;
using System.Text;
using System.Xml;
namespace XmlTextWriterFile
{
class Program
{
/*
* Create xml
*/
private static void createXML()
{
var xmlTextWriter = new XmlTextWriter("products.xml", Encoding.UTF8) {Formatting = Formatting.Indented};
//start the xml document
xmlTextWriter.WriteStartDocument();
//write the xml comment
xmlTextWriter.WriteComment("XML Document Commnet");
//start the element
xmlTextWriter.WriteStartElement("PRODUCT");
//write the xml element strings
xmlTextWriter.WriteElementString("NAME", "HP ELITEBOOK");
xmlTextWriter.WriteElementString("RAM", "4GB");
xmlTextWriter.WriteElementString("PROCESSOR", "Core i5");
xmlTextWriter.WriteElementString("HDD", "500 GB");
xmlTextWriter.WriteElementString("SCREEN", "15 inch");
//end xml element
xmlTextWriter.WriteEndElement();
//end the xml document
xmlTextWriter.WriteEndDocument();
//close this as well as the underlying stream
xmlTextWriter.Close();
Console.WriteLine(@"Check out /bin/debug folder in your project for the created xml file.");
}
/*
* Main method
*/
static void Main()
{
createXML();
Console.ReadKey();
}
}
}
How to Run
Just copy the Program.cs
file into your Console application. It has a main method and is runnable.