Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Created August 22, 2012 12:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihercowitz/3425176 to your computer and use it in GitHub Desktop.
Save ihercowitz/3425176 to your computer and use it in GitHub Desktop.
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
2012-07-04
******************************************************************************************
'''
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
else:
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
else:
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)
else:
if use_attributes:
node = node_parent.set(k, v)
else:
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')
x.xmlbuilder(receita={
'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