-
Step 1
Import the XML and IO namespaces to the project. The XMLTextWriter class is not automatically imported into new code files. Use the following syntax at the top of the page:
using System.IO;
using System.Xml; -
Step 2
Instantiate the class and create a new file. When instantiating the class, it requires a pointer to an XML file. In this example, the "myfile.xml" file is created:
XmlTextWriter myXML = new XmlTextWriter("myfile.xml", null); -
Step 3
Write the top, root element to the file. This is the main element that encapsulates all the item lists. This example creates a list of books. The root element used is "books":
myXML.WriteStartElement("books"); -
Step 4
Write the list of books using XML "item" tags. The following writes a list of books under the "books" element created in step 3:
myXML.WriteElementString("item", "My First Book");
myXML.WriteElementString("item", "My Second Book");
myXML.WriteElementString("item", "My Third Book"); -
Step 5
Close the root tag element. Just like HTML, XML needs a closing tag. The following code closes the tag:
myXML.WriteEndElement(); -
Step 6
Close the file. Closing the file frees resources on the server and releases it from being locked. If you forget to close the file, the server holds a "read" lock on it. The following syntax closes the file:
myXML.Close();











