This tutorial assumes that you already know the basics of XML as I will start directly to coding. To create or manipulate XML files, you must use the classes and methods inside the System.XML namespace of the .NET Framework.
Writing XML Files
We can use the XmlWriter class to write XML files. It allows you to write XML text into a stream and then save it into an xml file.
public class Program
public static void Main()
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("Products.xml", settings);
writer.WriteComment("This file is generated by the program.");
writer.WriteElementString("BrandName", "X Soap");
writer.WriteElementString("Manufacturer", "X Company");
We first import the System.Xml namespace. We use the XmlWriterSettings class to create a setting for the XmlWriter that we will use. We dictated the program to use proper indention when writing the xml by using this settings. We then create an XmlWriter object by calling the XmlWriter.Create method and supplying the filename and the XmlWriterSettings object.
Using the XmlWriter class, we can write our xml. We first use the XmlWriter.WriteStartDocument() method which writes the xml declaration you find on the top of most xml files. Next we create a sample comment using teh XmlWriter.WriteComment() method. To write an Xml Element, we use the XmlWriter.WriteStartElement() and supply the name of the element as the argument. The XmlWriter.WriteStartElement() must be paired with XmlWriter.WriteEndElement which writes the closing tag of that element. We now create some attributes for the element using the XmlWriter.WriteAttributeString() method and supply the name and the value for that attribute.
We used the XmlWriter.WriteElementString() method with a name and a value as the arguments to write an element that is wrapping a value. We then nested another element inside the Products element by writing one more set of XmlWriter.WriteStartElement() and XmlWriter.WriteEndElement() . Inside it, we add two more elements that contain values. To mark the end of the document, we simly call the XmlWriter.WriteEndDocument() method.
Finally, we used the XmlWriter.Flush() method to clean the contents of the stream and the XmlWriter.Close() method to save the file and stop the program from using it.
The above code will produce the following XML file contents:
<?xml version="1.0" encoding="utf-8"?>
<!--This file is generated by the program.-->
<Product ID="001" Name="Soap">