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.
I already did something and it is working but I am having trouble when I need to create different groups, something like this:
<?xml version="1.0" encoding="utf-8"?>
<CONFIG>
<General>
<Field1>192.168.0.2</Field1>
</General>
<Data>
<Field1>Joseph</Field1>
<Field2>Locked</Field2>
</Data>
</CONFIG>
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)!
I am using System.Linq, something like this:
To open document:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);
To save document:
xmlDoc.Save(FilePath);
To get value:
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;
}
To set value:
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)
{
}
}
The CreateGroup code:
public void createGroup(string Group)
{
try
{
XmlElement xmlComum = xmlDoc.CreateElement(Group);
xmlDoc.DocumentElement.AppendChild(xmlComum);
xmlDoc.Save(FilePath);
}
catch (Exception ex)
{
}
}