forked from zhanghe06/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_etree.py
More file actions
70 lines (55 loc) · 1.32 KB
/
test_etree.py
File metadata and controls
70 lines (55 loc) · 1.32 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
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: 23432.py
@time: 2016/10/10 下午10:43
"""
import xml.etree.ElementTree as ET
xml_str_test = """
<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>
"""
def print_node(node):
# print "attrib:%s" % node.attrib
print "tag:%s" % node.tag
print "text:%s" % node.text
def read_nodes(em):
print type(em), em
for child in em:
print_node(child)
read_nodes(child)
def xml_to_dict(xml_str):
"""
将xml转为dict
"""
dict_data = {}
root = ET.fromstring(xml_str)
dict_data[root.tag] = {}
print_node(root)
read_nodes(root)
def run():
xml_to_dict(xml_str_test)
if __name__ == '__main__':
run()