today I would like to share with you some python knowledge. I am fiddeling around with python and xml to generate HTTP Post messages. In this blog entry I describe in a brief way how you can create a xml structure and pretty print it.
I am using ElementTree, which does not support pretty printing using the pprint library. To circumvent this, I found this helpful webpage: http://effbot.org/zone/element-lib.htm#prettyprint
Now I would like to share some sample code to illustrate how you can use this function to make you xml look nice:
from xml.etree import ElementTree as ET ''' copy and paste from http://effbot.org/zone/element-lib.htm#prettyprint it basically walks your tree and adds spaces and newlines so the tree is printed in a nice way ''' def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i ''' function to build an example tree containing cars and ships vehicles is the root node ''' def buildTree(): vehicles = ET.Element("vehicles") cars = ET.SubElement(vehicles, "cars") cars.set("Type", "American") car1 = ET.SubElement(cars, "car") car1.text = "Ford Mustang" car2 = ET.SubElement(cars, "car") car2.text = "Dodge Viper" ships = ET.SubElement(vehicles, "ships") ships.set("Type", "sunken") ship1 = ET.SubElement(ships, "ship") ship1.text = "Titanic" indent(vehicles) tree = ET.ElementTree(vehicles) tree.write("vehicle_file.xml", xml_declaration=True, encoding='utf-8', method="xml") ''' main function, so this program can be called by python program.py ''' if __name__ == "__main__": buildTree()
Copy this source code to a new file “programm.py”. Open a terminal and run it with “python program.py“. The resulting file looks like this.
<?xml version='1.0' encoding='utf-8'?> <vehicles> <cars Type="American"> <car>Ford Mustang</car> <car>Dodge Viper</car> </cars> <ships Type="sunken"> <ship>Titanic</ship> </ships> </vehicles>
For more information about using ElementTree, please have a look at the official documentation: http://docs.python.org/2/library/xml.etree.elementtree.html I hope this is helpful, please comment.