forked from bulgarieil/python5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml_builder.py
More file actions
51 lines (39 loc) · 1.46 KB
/
xml_builder.py
File metadata and controls
51 lines (39 loc) · 1.46 KB
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
import xml.etree.ElementTree as ET
#pretty print method
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
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 subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
#root element
root = ET.Element('bookstore', {'specialty':'novel'})
#book sub-element
book = ET.SubElement(root, 'book', {'style':'autobiography'})
author = ET.SubElement(book, 'author')
firstName = ET.SubElement(author, 'first-name')
firstName.text = 'Joe'
lastName = ET.SubElement(author, 'last-name')
lastName.text = 'Bob'
award = ET.SubElement(author, 'award')
award.text = 'Trenton Literary Review Honorable Mention'
price = ET.SubElement(book, 'price')
price.text = str(12)
#magazine sub-element
magazine = ET.SubElement(root, 'magazine', {'style':'glossy', 'frequency':'monthly'})
price = ET.SubElement(magazine, 'price')
price.text = str(12)
subscription = ET.SubElement(magazine, 'subscription', {'price':'24', 'per':'year'})
#write to file
tree = ET.ElementTree(indent(root))
tree.write('bookstore2.xml', xml_declaration=True, encoding='utf-8')