I found that adding the following lines formats my
xml file:
w.Formatting = Formatting.Indented;
w.Indentation = 5;
Complete code snippet for writing to an XML file (C#)
using System;
using System.Xml;
using System.IO;
namespace WriteToXML
{
class Program
{
static void Main(string[] args)
{
string _path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
_path = _path.Substring(6, _path.Length - 6);
string _file = _path + "\\article.xml";
FileStream fs = new FileStream(_file, FileMode.Create);
XmlTextWriter w = new XmlTextWriter(fs, null);
w.Formatting = Formatting.Indented;
w.Indentation = 5;
w.WriteStartDocument();
w.WriteStartElement("articles");
w.WriteComment("This file was generated by the XmlTextWriter class");
w.WriteStartElement("article");
w.WriteStartElement("timestamp");
w.WriteString(DateTime.Now.ToString());
w.WriteEndElement();
w.WriteStartElement("subject");
w.WriteString("subject");
w.WriteEndElement();
w.WriteStartElement("body");
w.WriteString("This is a test");
w.WriteEndElement();
w.WriteStartElement("entryID");
w.WriteEndElement();
w.WriteStartElement("deleted");
w.WriteString("No");
w.WriteEndElement();
w.WriteEndElement();
w.WriteEndDocument();
w.Close();
}
}
}
NOTE:
1. Matthew MacDonald, Beginning ASP.NET 3.5 in C# 2008 2nd Edition
Publ. Apress. ISBN-13 978-1-59059-891-7. P. 647 to P.688