Here's a handly little class that i use very often to read/write XML files. Its a very handy little tool to save settings or anything else you wish to read/write often.
Hope you find it useful
Useage:
Hope you find it useful
Useage:
Code:
setting mySettings = new settings("myFile.xml");
// To Retrieve Values
string myString = mySettings.getSettings("myNodeName");
// To Set Values
mySetting.setSettings("myNodeName", "myValue");
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
namespace Jayfella.XMLParser
{
class Settings
{
private string xmlFile;
private XmlDocument xmldoc = new XmlDocument();
public Settings(string xmlFile)
{
this.xmlFile = xmlFile;
initXml();
}
private bool initXml()
{
try
{
xmldoc.Load(xmlFile);
}
catch (Exception)
{
TextWriter writer = new StreamWriter(xmlFile);
writer.WriteLine("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");
writer.WriteLine("<Settings>");
writer.WriteLine("</Settings>");
writer.Close();
}
return true;
}
public string getSetting(string settingNode)
{
xmldoc.Load(xmlFile);
XmlNodeList list = xmldoc.GetElementsByTagName("Settings");
try
{
foreach (XmlNode searchNode in list)
{
return searchNode.SelectSingleNode(settingNode.Replace(" ", "_")).InnerText;
}
}
catch (Exception)
{ }
return "";
}
public bool setSetting(string settingNode, string newValue)
{
xmldoc.Load(xmlFile);
XmlNodeList list = xmldoc.SelectNodes("Settings");
try
{
foreach (XmlNode searchNode in list)
{
XmlNode node = searchNode.SelectSingleNode(settingNode.Replace(" ", "_"));
if (node == null)
{
XmlElement element = xmldoc.CreateElement(settingNode.Replace(" ", "_"));
xmldoc.DocumentElement.AppendChild(element);
searchNode.SelectSingleNode(settingNode.Replace(" ", "_")).InnerText = newValue;
}
else
searchNode.SelectSingleNode(settingNode.Replace(" ", "_")).InnerText = newValue;
}
}
catch (Exception)
{ return false; }
xmldoc.Save(xmlFile);
return true;
}
}
}