Reading & Writing XML files in C#

On various occassions I havehad a need to either read XML files for input into a program or save XML iles for later use and possible shring with other programs.

XML reading/writing in C# is quite a simple task once you get the hang of it and understand the different node types.

1) Reading XML files:

Lets say we have a settings file and we need to be able to read it into our pogram. This settings file sits in our application path and has a simple peice of data that will tell us the location of other data. 

string flSettings = Application.StartupPath + "\\settings.xml"; //file to load setting (our xml file)
if (File.Exists(flSettings))
{
    XmlTextReader textReader = new XmlTextReader(flSettings); // create the xml object  and open the file
    while (textReader.Read()) // loop through and read each elemnt
    {
            XmlNodeType nType = textReader.NodeType; 
           // what type of node do we have? there are a few different types so check these out.
            if (nType == XmlNodeType.Text)
           {
                  // do something
           }
            if (nType == XmlNodeType.Text)
           {
                    // do simething else
          }
         //... and so on ...
    }
    textReader.Close();
}

2)

Writing the XML is simple as well, you simply need to understand the different node types and where to write them:

   XmlTextWriter textWriter = new XmlTextWriter(flSettings, null);
   textWriter.WriteStartDocument();
   textWriter.WriteStartElement("MyElement");
   textWriter.WriteString("MySring");
   textWriter.WriteEndElement();
   textWriter.WriteEndDocument();
   textWriter.Close();