| ||||||||
| This is just a little exercise of managing XML from Python. This the first time I manage XML with Python, so in this code there can be various problems: http://www.fantascienza.net/leonard It's meant as the Python version of the Perl code of the article: "XML for Perl developers, Part 1: XML plus Perl -- simply magic Integrate XML into a Perl application using XML::Simple", by Jim Dixon, 30 Jan 2007: http://www-128.ibm.com/developerworks/x The input XML of the article contains an error that I have fixed, and I have changed the dates some. More info inside my sourcecode. Requires Python 2.5 and mx.DateTime. Things to be done for this exercise: - To save space, change all of the subelements to attributes - Increase prices by 20% - Make all prices look the same, so all will show two decimal places - Sort the list [I sort it according to pet name] - Replace dates of birth with ages Input XML: <?xml version='1.0'?> <pets> <cat> <name>Madness</name> <dob>1 February 2004</dob> <price>150</price> </cat> <dog> <name>Maggie</name> <dob>12 October 2006</dob> <price>75</price> <owner>Rosie</owner> </dog> <cat> <name>Little</name> <dob>28 January 2007</dob> <price>25</price> </cat> </pets> Output XML: <?xml version='1.0'?> <pets> <cat age="9 days" name="Little" price="30.00" /> <cat age="3 years" name="Madness" price="180.00" /> <dog age="3 months" name="Maggie" owner="Rosie" price="90.00" /> </pets> I have found two problems: 1) By default attributes are sorted in lexical order when printed, so I can't see a way to put the "name" attribute first, to allow a simple reading of the XML file. 2) I have sorted the elements with some simple code, I don't know if there's a better way to sorte the Elements of an ElementTree: sorted_tree = sorted(root, key=lambda el:el.find("name").text)
for i in xrange(len(sorted_tree)):
root[i] = sorted_tree[i]
| ||||||||
| comments: Leave a comment |