XML Galore: Replacement for INI files
here are some functions that might come in handy
here is XML file before changes
Code:
<?xml version="1.0" standalone="no"?>
<ProgramSettings>
<Lingo>German</Lingo>
</ProgramSettings>
here are 2 lines of code, one to set a new value, and the other to read the value..
Code:
MessageBox.Show(myXML.setXMLNodeInXMLFile(Environment.CurrentDirectory + @"\settings.xml", "ProgramSettings", "Lingo", "Spanish"));
MessageBox.Show(myXML.getXMLNodeFromXMLFile(Environment.CurrentDirectory + @"\settings.xml", "ProgramSettings", "Lingo"));
here is the result
Code:
<?xml version="1.0" standalone="no"?>
<ProgramSettings>
<Lingo>Spanish</Lingo>
</ProgramSettings>
and here is the code
PHP Code:
//Descrtiption: All functions and methods related to XML
//File: myXML.cs
//Author Name: Kovan Abdulla
//Author Email: [email][email protected][/email]
//Author Homepage: [url]http://www.imetasoft.com[/url]
using System;
using System.Xml;
namespace CSharpDummyApp
{
public class myXML
{
private myXML()
{
}
public static string getXMLNodeFromXMLFile( string xmlFile,
string parentNode,
string node)
//PURPOSE: To retrieve the text between an xml tag from a xml file
//REQUIRED: the node or the text between xml tag and the parent of that node
//PROMOSE: return either file not found or the text of the given node
{
try
{
XmlDocument doc = new XmlDocument(); // get an XML document
doc.Load(xmlFile); //load the file
XmlNodeList xmlNode = doc.GetElementsByTagName(node);
for(int i = 0; i < xmlNode.Count; i++) //loop through all the found nodes
{
if (xmlNode[i].ParentNode.Name == parentNode) //find the one we want in the collection
{
return xmlNode[i].InnerText.ToString(); //return the text
}
}
return "Node belonging to " + parentNode + " was not found in " + xmlFile;
}
catch(System.Exception e) //catch the exception such as if the file passed in is not found
{
return e.Message;
}
}
public static string setXMLNodeInXMLFile( string xmlFile,
string parentNode,
string node,
string nodeValue)
//PURPOSE: To set the text between an xml tag in a xml file
//REQUIRED: the node or the text between xml tag and the parent of that node, and new text
//PROMOSE: return either file not found or success message
{
try
{
XmlDocument doc = new XmlDocument(); // get an XML document
doc.Load(xmlFile); //load the file
XmlNodeList xmlNode = doc.GetElementsByTagName(node);
for(int i = 0; i < xmlNode.Count; i++) //loop through all the found nodes
{
if (xmlNode[i].ParentNode.Name == parentNode) //find the one we want in the collection
{
xmlNode[i].InnerText = nodeValue; //set the text
doc.Save(xmlFile); //save the file back
return "Node " + node + "'s value has been changed to " + nodeValue + " succesfuly";
}
}
return "Node belonging to " + parentNode + " was not found in " + xmlFile;
}
catch(System.Exception e) //catch the exception such as if the file passed in is not found
{
return e.Message;
}
}
}
}