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 items.append(item) return items
There's a bug in your code. I suspect instead of
ReplyDeletev = 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'
Good pickup! Fixing now.
Delete