Python 3

Code examples for using ConfigAdapter from Python 3.


Go back

Source

This is the reference implementation of ConfigAdapter.Xml in Python 3. Other file formats are not available yet.

import xml.etree.ElementTree as ET

def From(path):
    """Open an existing XML configuration file."""
    tree = ET.parse(path);
    root = tree.getroot();
    return Config(path);

class Config:
    path = None;
    tree = None;
    root = None;

    def __init__(self, path):
        self.path = path;
        self.tree = ET.parse(self.path);
        self.root = self.tree.getroot();

    def Read(self, key):
        """Return the value of a setting."""
        element = self.root;
        fragments = key.split(":");
        for fragment in fragments:
            for tag in element:
                if tag.tag == fragment:
                    element = tag;
                    break;
        return element.text;

    def Write(self, key, value):
        """Create a new setting or modify the value of an existing one."""
        element = self.root;
        fragments = key.split(":");
        for fragment in fragments:
            existing = False;
            for tag in element:
                if tag.tag == fragment:
                    element = tag;
                    existing = True;
                    break;
            if existing == False:
                element.append(ET.Element(fragment));
                for tag in element:
                    if tag.tag == fragment:
                        element = tag;
                        break;
        element.text = str(value);
        self.tree.write(self.path);

Note the following limitations in the current functionality:

  • Reading or writing comments is not supported.
  • This Python code can produce nested section more than one level deep. The resulting file may not be compatible with the main C# library.

Use the code

Instruction on how to use the previous code.

For organizational purposes, it is reccomended to put the code in its own folder, like this: Root/ConfigAdapter/XmlConfig.py

Then, in your own code, import ConfigAdapter:

import ConfigAdapter.XmlConfig as Config;

Now you can start using it with a similar syntax to that of the main ConfigAdapter:

config = Config.From("ConfigFile.xml");

value = config.Read("Section:SettingName");
numeric = int(value);

config.Write("Section:SettingName", 42);
config.Write("Section:OtherSetting", "Value");

You're all done!

Now you can interact with Xml configuration files from Python 3 code.


Go back