-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseXml.py
More file actions
60 lines (53 loc) · 1.42 KB
/
parseXml.py
File metadata and controls
60 lines (53 loc) · 1.42 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
#!/usr/bin/python
import xml.etree.ElementTree as ET
strXml = '\
<?xml version="1.0"?>\
<data>\
<country name="Liechtenstein">\
<rank>1</rank>\
<year>2008</year>\
<gdppc>141100</gdppc>\
<neighbor name="Austria" direction="E"/>\
<neighbor name="Switzerland" direction="W"/>\
</country>\
<country name="Singapore">\
<rank>4</rank>\
<year>2011</year>\
<gdppc>59900</gdppc>\
<neighbor name="Malaysia" direction="N"/>\
</country>\
<country name="Panama">\
<rank>68</rank>\
<year>2011</year>\
<gdppc>13600</gdppc>\
<neighbor name="Costa Rica" direction="W"/>\
<neighbor name="Colombia" direction="E"/>\
</country>\
</data>'
#from file
#tree = ET.parse('country_data.xml')
#root = tree.getroot()
#from string
root = ET.fromstring(strXml)
for child in root:
print (child.tag, child.attrib)
for subchild in child:
print (subchild.tag)
print (subchild.attrib)
print (subchild.text)
print ('')
for child in root:
print ('Tag: ' + child.tag)
#print (child.attrib)
print ('Attribute [name]: ' + child.attrib['name'])
for subchild in child:
print ('Tag: ' + subchild.tag)
if subchild.attrib:
#print (subchild.attrib)
print ('Attribute [direction]: ' + subchild.attrib['direction'])
print ('Attribute [name]: ' + subchild.attrib['name'])
if subchild.text:
print ('Text: ' + subchild.text)
print ('')
for country in root.findall("./country"):
print('Name: ' + str( country.attrib['name'] ))