public
Created

Building a XML Tree as Easy as ABC in Python

  • Download Gist
xmlbuilder.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
'''
****************************************************************************************
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.