title: xml Class to substitute ini files
body: <p>I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files.</p>
  
  <p>I already did something and it is working but I am having trouble when I need to create different groups, something like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;CONFIG&gt;
    &lt;General&gt;
      &lt;Field1&gt;192.168.0.2&lt;/Field1&gt;
    &lt;/General&gt;
    &lt;Data&gt;
      &lt;Field1&gt;Joseph&lt;/Field1&gt;
      &lt;Field2&gt;Locked&lt;/Field2&gt;
    &lt;/Data&gt;
  &lt;/CONFIG&gt;
  </code></pre>
  
  <p>how can i specify that i want to read the field1 of [data] group?  note that i have same field name in both groups (Field1)!</p>
  
  <p>I am using System.Linq, something like this:</p>
  
  <p>To open document:</p>
  
  <pre><code>XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.Load(FilePath);
  </code></pre>
  
  <p>To save document:</p>
  
  <pre><code>xmlDoc.Save(FilePath);
  </code></pre>
  
  <p>To get value:</p>
  
  <pre><code>public string getValue(string Field)
  {
      string result = "";
      try
      {
          XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
          if (xmlComum.Item(0) == null)
              result = "";
          else
              result = xmlComum.Item(0).InnerText;
      }
      catch (Exception ex)
      {
          return "";
      }
      return result;
  }
  </code></pre>
  
  <p>To set value:</p>
  
  <pre><code>public void setValue(string Group, string Field, string FieldValue)
  {
      try
      {
          XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
          if (xmlComum.Item(0) == null)
          {
              xmlComum = xmlDoc.GetElementsByTagName(Group);
              if (xmlComum.Item(0) == null)
              {
                  // create group
                  createGroup(Group);
                  xmlComum = xmlDoc.GetElementsByTagName(Group);
              }
              XmlElement xmlE = xmlDoc.CreateElement(Field);
              XmlText xmlT = xmlDoc.CreateTextNode(FieldValue);
              xmlE.AppendChild(xmlT);
              xmlComum.Item(0).AppendChild(xmlE);
          }
          else
          {
              // item already exists, just change its value
              xmlComum.Item(0).InnerText = Value;
          }
          xmlDoc.Save(FilePath);
      }
      catch (Exception ex)
      {
      }
  }
  </code></pre>
  
  <p>The CreateGroup code:</p>
  
  <pre><code>public void createGroup(string Group)
  {
      try
      {
          XmlElement xmlComum = xmlDoc.CreateElement(Group);
          xmlDoc.DocumentElement.AppendChild(xmlComum);
          xmlDoc.Save(FilePath);
      }
      catch (Exception ex)
      {
      }
  }
  </code></pre>