Lachlan's misadventures in games programming

Thursday, 14 August 2014

Python - Parsing XML to Object

8/14/2014 12:50:00 am Posted by Lachlan , 2 comments
My apologies for it having been a while.

In the course of programming a roguelike in Python, I wrote the following chunk of code which might be helpful to others. Given a filename of an XML file and a constructor, it parses the XML file and uses the constructor to fill the object with the contents of the XML file (so - a field called 'SPAM' in the XML file would automatically populate the variable SPAM in the object created by the constructor). If the variable is a boolean or integer, it'll copy the XML as such.
import xml.etree.ElementTree as ET

def parse(filename, objectConstructor):
    tree = ET.parse(filename)
    root = tree.getroot()
    items = []
    for i in root:
        item = objectConstructor()
        for j in i:
            t = item.__dict__[j.tag]
            v = j.text
            if isinstance(t, bool):
                v = v == 'true'
            elif isinstance(t, int):
                v = int(v)          
            item.__dict__[j.tag] = v
    return items


  1. There's a bug in your code. I suspect instead of

    v = True if v == 'true' else 'false'

    you want:

    v = True if v == 'true' else False

    though that could equally as well be written:

    v = v == 'true'