Saturday, July 11, 2009

Reading from and Writing to simple XML Files in .Net

While developing applications it is often required to store and communicate data using XML Files. The following XML Access Class is made with the purpose to simplify the process of accessing XML Files. The code is in C#.Net.


// Class for reading and writing to xml files

class XML_Access
{
private XmlDocument xdoc;
private XmlElement root;
private XmlNode xn;
private XmlNodeList nodelist;
private XmlAttributeCollection xattr;


// Constructor load settings from specified xml file eg: config.xml

public XML_Access(string filename)
{
xdoc = new XmlDocument();
xdoc.Load(filename);
}

// Read specified Element value from xml file

public virtual string ReadXMLConfig(string ElementName)
{
nodelist = xdoc.GetElementsByTagName(ElementName);
return nodelist[0].InnerText;

}


// Read an Elements attributes

public virtual double ReadXMLAttributes(string ElementName,string Attribute)
{
nodelist = xdoc.GetElementsByTagName(ElementName);
xattr=nodelist[0].Attributes;
return double.Parse(xattr[Attribute].Value);
}

// Returns specified element's specified attribute in String format

public virtual string ReadXMLAttributesToString(string ElementName, string Attribute)
{
nodelist = xdoc.GetElementsByTagName(ElementName);
xattr = nodelist[0].Attributes;
return xattr[Attribute].Value.ToString();
}


// Edit specific element in xml file

public virtual void WriteXMLConfig(string ElementName,string Value,string FileName)
{
root = xdoc.DocumentElement;
xn = root.SelectSingleNode(ElementName);
xn.InnerXml = Value;
xdoc.Save(FileName);
}

// Edit specific element's specified attributes in xml file

public virtual void WriteXMLAttributes(string ElementName,string Attribute, string Value,string FileName)
{
root = xdoc.DocumentElement;
xn = root.SelectSingleNode(ElementName);
xattr = xn.Attributes;
xattr[Attribute].InnerXml = Value;
xdoc.Save(FileName);
}
}


All you will need to do is to declare an object of this class and use its simplified methods in your application

No comments:

Post a Comment