|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +Example of how to save data as xml, using the element tree module |
| 5 | +
|
| 6 | +This version does the full-on nested XML |
| 7 | +
|
| 8 | +""" |
| 9 | + |
| 10 | +import xml.etree.ElementTree as ET |
| 11 | +from indent_etree import indent # for prettier output |
| 12 | + |
| 13 | +outfilename = "add_book_data2.xml" |
| 14 | + |
| 15 | +# get the data from the py file |
| 16 | +from add_book_data import AddressBook |
| 17 | + |
| 18 | +# build a tree structure |
| 19 | +root = ET.Element("address_book") |
| 20 | + |
| 21 | +# add the elements: |
| 22 | +for person in AddressBook: |
| 23 | + p = ET.SubElement(root, "person") |
| 24 | + # This method stores everything as sub-elements |
| 25 | + for key, value in person.items(): |
| 26 | + if type(value) == dict: |
| 27 | + address = ET.SubElement(p, 'address') |
| 28 | + for sub_key, sub_value in value.items(): |
| 29 | + sub_el = ET.SubElement(address, sub_key) |
| 30 | + sub_el.text=sub_value |
| 31 | + else: |
| 32 | + el = ET.SubElement(p, key) |
| 33 | + el.text=value |
| 34 | + |
| 35 | +# wrap it in an ElementTree instance, and save as XML |
| 36 | +tree = ET.ElementTree(root) |
| 37 | + |
| 38 | +indent(tree.getroot()) # to make it more pretty |
| 39 | +tree.write(outfilename) |
| 40 | + |
| 41 | +### See if we can re-load it |
| 42 | + |
| 43 | +tree = ET.parse(outfilename) |
| 44 | +book = tree.getroot() |
| 45 | +# re-build the original list: |
| 46 | +AddressBook2 = [] |
| 47 | +for person in list(book): |
| 48 | + p = {} |
| 49 | + for sub_el in list(person): |
| 50 | + if sub_el.tag == "address": |
| 51 | + address = {} |
| 52 | + for sub_sub_el in sub_el.getchildren(): |
| 53 | + t = sub_sub_el.text |
| 54 | + if t is None: ## etree returns None for empty tags! |
| 55 | + address[sub_sub_el.tag] = "" |
| 56 | + else: |
| 57 | + address[sub_sub_el.tag] = t |
| 58 | + p['address'] = address |
| 59 | + else: |
| 60 | + p[sub_el.tag] = sub_el.text |
| 61 | + AddressBook2.append(p) |
| 62 | + |
| 63 | +if AddressBook2 == AddressBook: |
| 64 | + print "xml version is the same as the original" |
| 65 | +else: |
| 66 | + print "xml version is not exactly the same as the original" |
0 commit comments