Methods to create, update and get the data from XML file.
Introduction:
Some time we need to save some temporary data to in XML file, this post will give you some best methods to create , update and get the data.
You can download the full code here
Required Namespace:
using System.Xml;
using System.IO;
Method to create XML File
private static readonly string
fileName = "{0}Xfile.xml"; //Define the name of XML file
public static void CreateXmlFile()
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string strConfigFile = string.Format(fileName,
path + "\\");
if (!File.Exists(strConfigFile))
{
FileStream fs = new FileStream(strConfigFile,
FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
w.WriteStartDocument();
w.WriteStartElement("DATA");
w.WriteEndDocument();
w.Flush();
fs.Close();
}
}
catch (Exception
ex)
{
}
}
Method to update data to XML File
public static void UpdateXml(string
key, string value)
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//Define the path to save the XML file
string strDataFile = string.Format(fileName, path + "\\");
XmlDocument dom = new XmlDocument();
dom.Load(strDataFile);
Boolean keyFind = false;
XmlNodeList nodeslist =
dom.SelectNodes("/DATA/Add");
foreach (XmlNode
xn in nodeslist)
{
string keyInner = xn["key"].InnerText;
if (keyInner == key)
{
keyFind = true;
xn["value"].InnerText = value;
break;
}
}
if (!keyFind)
{
XmlNode rootNode =
dom.SelectSingleNode("/DATA");
XmlNode newNode =
rootNode.AppendChild(dom.CreateNode(XmlNodeType.Element,
"Add",
dom.DocumentElement.NamespaceURI));
XmlNode keyNode =
newNode.AppendChild(dom.CreateNode(XmlNodeType.Element,
"key",
dom.DocumentElement.NamespaceURI));
keyNode.InnerText = key;
XmlNode valNode =
newNode.AppendChild(dom.CreateNode(XmlNodeType.Element,
"value",
dom.DocumentElement.NamespaceURI));
valNode.InnerText = value;
}
dom.Save(strDataFile);
}
catch (Exception
ex)
{
}
}
Method to Get data from XML File
public static string
GetValuefromKey(string key)
{
string val = "";
try
{
string path =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string strConfigFile = string.Format(fileName, path + "\\");
XmlDocument dom = new XmlDocument();
dom.Load(strConfigFile);
XmlNodeList nodeslist =
dom.SelectNodes("/DATA/Add");
foreach (XmlNode
xn in nodeslist)
{
string keyInner = xn["key"].InnerText;
if (keyInner == key)
{
val = xn["value"].InnerText;
}
}
}
catch (Exception
ex)
{
}
return (val); ;
}