The XMLTextWriter class is part of the System.Xml namespace. This class contains several methods to aid in the creation of XML files from start to finish.
There are four steps to create a properly formed XML file
- Instantiate an XmlTextWriter object
- Write the XML declaration node
- Write the data
- Close the file and perform clean-up
–
Common Methods (Full List)
–
C# Code Sample
1: using System;
2: using System.IO;
3: using System.Xml;
4:
5: namespace xmlSample
6: {
7: public class Sample
8: {
9: public static void Main()
10: {
11: // -- Intantiate the XmlTextWriter object
12: XmlTextWriter xmlWrite = new XmlTextWriter(@"c:\temp\MusicGroups.xml", null);
13:
14: // -- Write the version line
15: xmlWrite.WriteStartDocument();
16:
17: // -- Write a description comment
18: xmlWrite.WriteComment("Some of my favorite groups");
19:
20: // -- Start the root element
21: xmlWrite.WriteStartElement("CoolGroups");
22:
23: // -- Write list elements
24: xmlWrite.WriteElementString("group", "Breaking Benjamin");
25: xmlWrite.WriteElementString("group", "Incubus");
26: xmlWrite.WriteElementString("group", "311");
27: xmlWrite.WriteElementString("group", "Staind");
28: xmlWrite.WriteElementString("group", "Lifehouse");
29:
30: // -- End the root element
31: xmlWrite.WriteEndElement();
32:
33: // -- Write to the XML file and close the writer
34: xmlWrite.Close();
35: }
36: }
37: }
–
Result
–
The XmlTextWriter class does much more than what I have written about here. There is a great article by Scott Mitchell that goes into much more detail on this very useful and powerful class.
–