-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry.py
More file actions
61 lines (44 loc) · 1.44 KB
/
try.py
File metadata and controls
61 lines (44 loc) · 1.44 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
52
53
54
55
56
57
58
59
60
61
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()