using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; //add the xml namespace namespace MakeXMLDocumentDOM /***************************************************** * this program creates a simple xml document * that can store a few settings for * a windows form. It uses the DOM model as * implemented in the XmlDocument object of * .Net * ************************************************/ { class Program { static void Main(string[] args) { //call the method makexml(); Console.ReadKey(); } static void makexml() { //get the current date. we will use this later //in the xml string currentDate = DateTime.Now.ToShortDateString(); //declare a new xml document XmlDocument doc = new XmlDocument(); //create an XML declaration XmlDeclaration declaration =doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); //append it to the document doc.AppendChild(declaration); //do the same for a comment XmlComment comment = doc.CreateComment("This document stores session settings"); doc.AppendChild(comment); //now we create the root element XmlElement settingsRoot = doc.CreateElement("settings"); //create and set the value for an attribute settingsRoot.SetAttribute("setdate", currentDate); //append to the document doc.AppendChild(settingsRoot); //now we create a second element XmlElement font = doc.CreateElement("fontcolor"); //provide the inner text value font.InnerText = "White"; //append it not to the document but to the root element settingsRoot.AppendChild(font); /************************************************ * The rest of the elements follow exactly the same * pattern * ********************************************/ XmlElement title = doc.CreateElement("formtitle"); title.InnerText = "XML User Settings"; settingsRoot.AppendChild(title); XmlElement back = doc.CreateElement("formbackcolor"); back.InnerText = "Navy"; settingsRoot.AppendChild(back); XmlElement lbltxt = doc.CreateElement("labeltext"); lbltxt.InnerText = "Hello from the settngs file"; settingsRoot.AppendChild(lbltxt); //we create an xml writer and direct its output //to the console so we can see what we have wrought XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; doc.WriteTo(writer); //make sure you close the writer or it won't //release the file writer.Close(); //a second xmlwriter directed to a file on disk //You will have to modify the path to the file XmlTextWriter writerb = new XmlTextWriter(@"C:\Users\Steve\Desktop\settings.xml",Encoding.UTF8); writerb.Formatting = Formatting.Indented; doc.WriteTo(writerb); writerb.Close(); } } }