[c#] XML Reader / Writer

Status
Not open for further replies.

jayfella

Active Member
1,600
2009
565
700
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:

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;
        }
    }
}
 
13 comments
im still noob at this, put can you directly use the XML Namespace to allocate the settings class ?

eg:
PHP:
namespace System.Xml
{
    class jaysParser
    {
       /*....*/
    }
}
 
yep.

you can either do:

using Jayfella.XMLParser;

in the top with the rest, or just

Jayfellla.XMLParser.Settings mySettings = new Settings("myFile.xml")

Either way works.
 
yea its ok i thought to myself as i like ordered code that you should extend the xmlParser to the XML Namespace but wasn't sure if your allowed to implement user namepaces into a system namespace :/

:)
 
Nice example. I personally would remove all try-catch blocks though :).
Also, who can spot what's wrong with:
PHP:
        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 "";
        }
. :p

Edit:
Xdocument + Linq queries > XmlDocument.
 
wut !

/8char

Edit:

foreach (XmlNode searchNode in list)

list is a special operator and not a variable! in defines what variable it is traversing so it should be

foreach (searchNode in XmlNode)


or you should not be using list in the above variable setter
//maybeee
 
I try/catched it for a reason, i forget why now.. lemme think.

oh oh - user account control - its not enough to try/catch it normally, it fails inside the class if the program is denied write permissions.

EDIT: Yeah i know, no catch routine. so shoot me :P
 
I know jay, but you don't need to try-catch there, you need to if-else.

Anyways:
PHP:
                foreach (XmlNode searchNode in list)
                {
                    return searchNode.SelectSingleNode(settingNode.Replace(" ", "_")).InnerText;
                }

Why start a loop when you have a return statement in the 1st iteration >_>?
 
nigger i know that >.>

Code:
                     /"\
                    |\./|
                    |   |
                    |   |
                    |>~<|
                    |   |
                 /'\|   |/'\..
             /~\|   |   |   | \
            |   =[@]=   |   |  \
            |   |   |   |   |   \
            | P   W   N   D |`   )
            |                   /
             \                 /
              \               /
               \    _____    /
                |--//''`\--|
                | (( +==)) | <=== Pwning Time xD
                |--\_|_//--|
 
I'd just check that as soon as you declare list:
Code:
if (list.Count == 0) return String.Empty;

If the code runs after that you know there are nodes, thus no need for a try-catch. They are resource eaters :).
 
PHP:
public string getSetting(string settingNode)
        {
            xmldoc.Load(xmlFile);
            XmlNodeList list = xmldoc.GetElementsByTagName("Settings");
           
            if (list.Count == 0) return String.Empty;

            return searchNode.SelectSingleNode(settingNode.Replace(" ", "_")).InnerText;

        }

Like so :) Coderz Corner ftw. Who said it was a crap idea.
 
Status
Not open for further replies.
Back
Top