Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Created July 6, 2012 19:37
Show Gist options
  • Save ihercowitz/3062327 to your computer and use it in GitHub Desktop.
Save ihercowitz/3062327 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
Sample:
print etree.tostring(xmlbuilder("main", unique=True,
produtos=dict(produto=dict(codigo="UFC153",
descricao="Cueca Velha",
quantidade="2",
preco="10.00",
peso="2.00",
frete="0.00",
desconto="0.00"))), pretty_print=True)
Created by Igor Hercowitz
2012-07-04
******************************************************************************************
'''
from lxml import etree
def xmlbuilder(parent, unique=False, use_attributes=False, **kwargs):
if isinstance(parent, etree._Element):
node_parent = parent
else:
node_parent = etree.Element(parent)
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)
xmlbuilder(node, 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
return node_parent
if __name__ == "__main__":
root = etree.Element("main")
xmlbuilder(root, unique=True, use_attributes=True,
produtos=dict(produto=dict(codigo="UFC153",
descricao="Cueca Velha",
quantidade="2",
preco="10.00",
peso="2.00",
frete="0.00",
desconto="0.00")))
xmlbuilder(root, unique=True, use_attributes=True,
produtos=dict(produto=dict(codigo="SONIC",
descricao="Porco espinho camarada",
quantidade="20",
preco="4.00",
peso="2.00",
frete="0.00",
desconto="0.00")))
print etree.tostring(root, pretty_print=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment