Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Created April 3, 2021 13:00
Show Gist options
  • Save jvmvik/961401666d92831f01a64c38444ada62 to your computer and use it in GitHub Desktop.
Save jvmvik/961401666d92831f01a64c38444ada62 to your computer and use it in GitHub Desktop.
Dynamic Python object creation
# data
data = '''<?xml version="1.0" encoding="UTF-8"?>
<menza>
<date day="Monday">
<meal name="Potato flat cakes">
<ingredient name="potatoes"/>
<ingredient name="flour"/>
<ingredient name="eggs"/>
</meal>
<meal name="Pancakes">
<ingredient name="milk"/>
<ingredient name="flour"/>
<ingredient name="eggs"/>
</meal>
</date>
</menza>'''
# load
import xml.etree.ElementTree as ET
menza_xml_tree = ET.fromstring(data)
obj = xml2py(menza_xml_tree)
# test
for date in obj.date:
print(date.day)
for meal in date.meal:
print('\t', meal.name)
for ingredient in meal.ingredient:
print('\t\t', ingredient.name)
def xml2py(node):
"""
convert xml to python object
node: xml.etree.ElementTree object
"""
name = node.tag
pytype = type(name, (object, ), {})
pyobj = pytype()
for attr in node.attrib.keys():
setattr(pyobj, attr, node.get(attr))
if node.text and node.text != '' and node.text != ' ' and node.text != '\n':
setattr(pyobj, 'text', node.text)
for cn in node:
if not hasattr(pyobj, cn.tag):
setattr(pyobj, cn.tag, [])
getattr(pyobj, cn.tag).append(xml2py(cn))
return pyobj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment