-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathex_06_xml_examples.py
49 lines (35 loc) · 1.21 KB
/
ex_06_xml_examples.py
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
import xml.etree.ElementTree as ET
root = ET.parse('canteen.xml') #ElementTree instance
datums = root.findall('date') #list of Elements
for date in dates:
print(datum.attrib['day'])
meals = datum.iter('meal')
for meal in meals:
print('\t' + meal.attrib['name'])
for ingredience in meal.iter('ingredience'):
print('\t\t' + ingredience.attrib['name'])
def xml2py(node):
name = node.tag
pytype = type(name, (object, ), {})
pyobj = pytype()
for attr in node.attrib.keys():
setattr(pyobj, attr, node.get(attr))
if node.text and node.text != '' and node.text != ' ' \
and node.text != '\n':
setattr(pyobj, 'text', node.text)
for cn in node:
if not hasattr(pyobj, cn.tag):
setattr(pyobj, cn.tag, [])
getattr(pyobj, cn.tag).append(xml2py(cn))
return pyobj
xml_string = ''
with open('canteen.xml', 'rt') as f:
xml_string = f.read()
menza_xml_tree = ET.fromstring(xml_string)
obj = xml2py(menza_xml_tree)
for date in obj.date:
print(datum.day)
for meal in date.meal:
print('\t' + meal.name)
for ingredience in meal.ingredience:
print('\t\t' + ingredience.name)