Create a gist now

Instantly share code, notes, and snippets.

Building a XML Tree as Easy as ABC in Python
Building a XML Tree as Easy as ABC in Python
This implementation requires lxml
Created by Igor Hercowitz
from lxml import etree
class XmlBuilder:
def __init__(self, root_name='root'):
self.root = etree.Element(root_name)
self.pretty_print = True
def set_prettyprint(self, choice):
if isinstance(choice, bool):
self.pretty_print = choice
raise TypeError('This value should be a boolean')
def xmlbuilder(self, parent=None, unique=True, use_attributes=False, **kwargs):
use_attributes = False
if parent is None:
parent = self.root
if isinstance(parent, etree._Element):
node_parent = parent
node_parent = etree.Element(parent)
if 'attributes' in kwargs:
for k, v in kwargs['attributes'].items():
kwargs[k] = v
use_attributes = True
del kwargs['attributes']
for k, v in kwargs.items():
node = None
if unique and node_parent.find(k) is not None:
node = node_parent.find(k)
if isinstance(v, dict):
if node is None:
node = etree.SubElement(node_parent, k)
self.xmlbuilder(node, unique=False, use_attributes=use_attributes, **v)
if use_attributes:
node = node_parent.set(k, v)
node = etree.SubElement(node_parent, k)
node.text = v
use_attributes = False
return node_parent
def __str__(self):
return etree.tostring(self.root, pretty_print=self.pretty_print)
if __name__ == "__main__":
x = XmlBuilder('receitas')
'titulo': 'Bolo de Chocolate',
'ingredientes': {'attributes': { 'manteiga': '1 xicara',
'acucar': '2 xicaras',
'ovo': '4',
'farinha': '2 xicaras e 1/2 de farinha de trigo com fermento',
'leite': '1 copo'}},
'preparo': 'Misture os ingredientes, bote numa forma untada com manteiga e trigo.'\
'Depois coloque no forno. Por ultimo, faca a cobertura.'
print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment