Settings File

From IronPython Cookbook

This example shows how to use Xml to create a simple settings file for configuration of an application. The __main__ section shows how to use the class and runs through the features.

One interesting part is the use of dict.fromkeys to remove duplicates from the Category list. If using this code in your own application, please note the (current) lack of error handling!

import clr
clr.AddReference('System.Xml')
from System.Xml import XmlDocument
from System.IO import File

BasicXml = "<?xml version=\"1.0\"?><Settings></Settings>";

class AppSettings(object):
    def __init__(self):
        self._FilePath = ""
        self._SetUp(BasicXml)
    def _SetUp(self, Xml):
        self.Document = XmlDocument()
        self.Document.LoadXml(Xml)
    def Get(self, Name):
        Value = self.Document.SelectSingleNode("/Settings/" + Name).InnerText
        return Value
    def Set(self, Name, Value, Category=""):
        OldNode = self.Document.SelectSingleNode("/Settings/" + Name)
        if OldNode!=None:
            self.Document.SelectSingleNode("/Settings").RemoveChild(OldNode)
        ValNode = self.Document.CreateElement(Name)
        if Category!="":
            CategoryAttrib = self.Document.CreateAttribute("Category")
            CategoryAttrib.Value = Category
            ValNode.Attributes.Append(CategoryAttrib)
        ValNode.InnerText = Value
        self.Document.DocumentElement.AppendChild(ValNode)
    def Load(self, FilePath):
        self._FilePath = FilePath
        rawXML = File.ReadAllText(self._FilePath)
        self._SetUp(rawXML)
    def Save(self, FilePath):
        self._FilePath = FilePath
        rawXML = File.WriteAllText(self._FilePath, self.Document.OuterXml)
    def Output(self):
        print self.Document.OuterXml
    def AsList(self):
        ns = self.Document.SelectNodes("/Settings")
        SettingList = []
        for n in ns:
            for on in n.ChildNodes:
                Item = {}
                Item['Name'] = on.Name
                Item['Value'] = on.InnerText
                Item['Category'] = on.GetAttribute("Category")
                SettingList.append(Item)
        return SettingList
    def Categories(self):
        ns = self.Document.SelectNodes("/Settings")
        CatList = []
        
        for n in ns:
            for on in n.ChildNodes:
                cat = on.GetAttribute("Category")
                if len(cat)>0:
                    CatList.append(cat)
        return dict.fromkeys(CatList).keys()

if __name__ == "__main__":
    
    print "Create settings object."
    MySettings = AppSettings()
    
    print "Set a few values."
    MySettings.Set("Dog", "Dandy")
    MySettings.Set("Cat", "Cola")
    print "XML:"
    MySettings.Output()
    
    print "Get Settings"
    print "[" + MySettings.Get("Dog") + "]"
    print "[" + MySettings.Get("Cat") + "]"
    print "XML:"
    MySettings.Output()
    
    print "Save to file."
    MySettings.Save("test.xml")
    
    print "Load Settings into another object."
    MoreSettings = AppSettings()
    MoreSettings.Load("test.xml")
    
    print "Fetch value :" + MoreSettings.Get("Dog")
    print "Fetch value :" + MoreSettings.Get("Cat")
    
    print "Update Value:"
    MoreSettings.Set("Cat", "Moggy")
    print "XML:"
    MoreSettings.Output()
    
    print "Update Value:"
    MoreSettings.Set("Dog", "Cola", "Springer")
    print "XML:"
    MoreSettings.Output()
    
    print "Add Value:"
    MoreSettings.Set("Hamster", "Giles", "Rodent")
    print "XML:"
    MoreSettings.Output()
    
    print "--Walk through a list of the settings."
    for item in MoreSettings.AsList():
        print item['Name'] + "\t" + item['Value']  + "\t" + item['Category']
        
    print "--Print All Categories."
    for category in MoreSettings.Categories():
        print category
    print "--"
    print "Save to file."
    MySettings.Save("test.xml")


Back to Contents.

TOOLBOX
LANGUAGES