设为首页 收藏本站
查看: 903|回复: 0

[经验分享] python开发_xml.etree.ElementTree_XML文件操作_该模块在操作XML数据是存在安全隐患_慎用

[复制链接]

尚未签到

发表于 2015-4-27 11:06:01 | 显示全部楼层 |阅读模式
  xml.etree.ElementTree模块实现了一个简单而有效的用户解析和创建XML数据的API。
  在python3.3版本中,该模块进行了一些修改:
  xml.etree.cElementTree模块被弃用。
  警告:xml.etree.ElementTree模块在解析恶意构造的数据会产生一定的安全隐患。所以使用该模块的时候需要谨慎。
  下面来看看该模块是怎样解析和创建XML数据文档的。
  首先,我们应该了解一下什么是XML树和元素,XML是一种固有的层次化数据格式,这是一种最自然的格式类表示一棵树。
  xml.etree.ElementTree(简写ET)就此而言,ElementTree代表的是整个XML无奈的和元素的一棵树,这棵树有一个唯一的
  root根节点。在根节点下面,可以有很多子节点,而每一个子节点又可以有自己的属性或子节点....
  我们今天需要解析的XML文件的内容如下:
  我把该XML文件保存在:c:\\test\\hongten.xml文件中



1
2
3     
4         Hongten
5         M
6         20
7         97
8         90
9     
10     
11         DuDu
12         W
13         21
14         87
15         96
16     
17     
18         Sum
19         M
20         19
21         64
22         98
23     
24
  在上面的XML文件内容中,我们可以看到此XML文件的根节点为:students
    我们可以通过下面的方法获取到根节点



1 import xml.etree.ElementTree as ET
2 tree = ET.parse('c:\\test\\hongten.xml')
3 root = tree.getroot()
4 tag = root.tag          #students
  同样的我们也可以获取到根节点的属性



1 attrib = root.attrib     #{}
  因为根节点:students是没有属性的,所以为空。
  我们要获取根节点:students的子节点名称和属性



1  for child in root:
2      print(child.tag, child.attrib)
  输出为:



student {'no' : '2009081097'}
student {'no' : '2009081098'}
student {'no' : '2009081099'}
  我们同样可以获取属性对应的值



1 for student in root.findall('student'):
2     no = student.get('no')
3     name = student.find('name').text
4     print(no, name)
  输出为:



2009081097 Hongten
2009081098 DuDu
2009081099 Sum
  当然,我们也可以修改XML文件的内容:



1 for age in root.iter('age'):
2     new_age = int(age.text) + 1
3     age.text = str(new_age)
4     age.set('updated', 'yes')
5 tree.write('c:\\test\\hongten_update.xml')
  修改后的XML文件内容如下:



1
2     
3         Hongten
4         M
5         21
6         97
7         90
8     
9     
10         DuDu
11         W
12         22
13         87
14         96
15     
16     
17         Sum
18         M
19         20
20         64
21         98
22     
23
  ==================================================================
  以下是我对xml.etree.ElementTree模块进行了一些封装
  ==================================================================



  1 # -*- coding: utf-8 -*-
  2 #python xml.etree.ElementTree
  3
  4 #Author   :   Hongten
  5 #Mailto   :   hongtenzone@foxmail.com
  6 #Blog     :   http://www.iyunv.com/hongten
  7 #QQ       :   648719819
  8 #Version  :   1.0
  9 #Create   :   2013-09-03
10
11 import os
12 import xml.etree.ElementTree as ET
13
14 '''
15     在python中,解析XML文件有很多中方法
16     本文中要使用的方法是:xml.etree.ElementTree      
17 '''
18 #global var
19 #show log
20 SHOW_LOG = True
21 #XML file
22 XML_PATH = None
23
24 def get_root(path):
25     '''parse the XML file,and get the tree of the XML file
26     finally,return the root element of the tree.
27     if the XML file dose not exist,then print the information'''
28     if os.path.exists(path):
29         if SHOW_LOG:
30             print('start to parse the file : [{}]'.format(path))
31         tree = ET.parse(path)
32         return tree.getroot()
33     else:
34         print('the path [{}] dose not exist!'.format(path))
35
36 def get_element_tag(element):
37     '''return the element tag if the element is not None.'''
38     if element is not None:
39         if SHOW_LOG:
40             print('begin to handle the element : [{}]'.format(element))
41         return element.tag
42     else:
43         print('the element is None!')
44
45 def get_element_attrib(element):
46     '''return the element attrib if the element is not None.'''
47     if element is not None:
48         if SHOW_LOG:
49             print('begin to handle the element : [{}]'.format(element))
50         return element.attrib
51     else:
52         print('the element is None!')
53
54 def get_element_text(element):
55     '''return the text of the element.'''
56     if element is not None:
57         return element.text
58     else:
59         print('the element is None!')
60
61 def get_element_children(element):
62     '''return the element children if the element is not None.'''
63     if element is not None:
64         if SHOW_LOG:
65             print('begin to handle the element : [{}]'.format(element))
66         return [c for c in element]
67     else:
68         print('the element is None!')
69
70 def get_elements_tag(elements):
71     '''return the list of tags of element's tag'''
72     if elements is not None:
73         tags = []
74         for e in elements:
75             tags.append(e.tag)
76         return tags
77     else:
78         print('the elements is None!')
79
80 def get_elements_attrib(elements):
81     '''return the list of attribs of element's attrib'''
82     if elements is not None:
83         attribs = []
84         for a in elements:
85             attribs.append(a.attrib)
86         return attribs
87     else:
88         print('the elements is None!')
89
90 def get_elements_text(elements):
91     '''return the dict of element'''
92     if elements is not None:
93         text = []
94         for t in elements:
95             text.append(t.text)
96         return dict(zip(get_elements_tag(elements), text))
97     else:
98         print('the elements is None!')
99
100 def init():
101     global SHOW_LOG
102     SHOW_LOG = True
103     global XML_PATH
104     XML_PATH = 'c:\\test\\hongten.xml'
105
106 def main():
107     init()
108     #root
109     root = get_root(XML_PATH)
110     root_tag = get_element_tag(root)
111     print(root_tag)
112     root_attrib = get_element_attrib(root)
113     print(root_attrib)
114     #children
115     children = get_element_children(root)
116     print(children)
117     children_tags = get_elements_tag(children)
118     print(children_tags)
119     children_attribs = get_elements_attrib(children)
120     print(children_attribs)
121
122     print('#' * 50)
123     #获取二级元素的每一个子节点的名称和值
124     for c in children:
125         c_children = get_element_children(c)
126         dict_text = get_elements_text(c_children)
127         print(dict_text)
128     
129 if __name__ == '__main__':
130     main()
  运行效果:



Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
start to parse the file : [c:\test\hongten.xml]
begin to handle the element : []
students
begin to handle the element : []
{}
begin to handle the element : []
[, , ]
['student', 'student', 'student']
[{'no': '2009081097'}, {'no': '2009081098'}, {'no': '2009081099'}]
##################################################
begin to handle the element : []
{'score': '90', 'gender': 'M', 'name': 'Hongten', 'age': '20'}
begin to handle the element : []
{'score': '96', 'gender': 'W', 'name': 'DuDu', 'age': '21'}
begin to handle the element : []
{'score': '98', 'gender': 'M', 'name': 'Sum', 'age': '19'}
>>>
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-61170-1-1.html 上篇帖子: Linux下Python实现有道词典 下篇帖子: Pydev 的覆盖率测试python coverage以及其他使用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表