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

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文件中

 <?xml version="1.0" encoding="UTF-8"?>
<students>
<student no="2009081097">
<name>Hongten</name>
<gender>M</gender>
<age>20</age>
<score subject="math">97</score>
<score subject="chinese">90</score>
</student>
<student no="2009081098">
<name>DuDu</name>
<gender>W</gender>
<age>21</age>
<score subject="math">87</score>
<score subject="chinese">96</score>
</student>
<student no="2009081099">
<name>Sum</name>
<gender>M</gender>
<age>19</age>
<score subject="math">64</score>
<score subject="chinese">98</score>
</student>
</students>

在上面的XML文件内容中,我们可以看到此XML文件的根节点为:students
我们可以通过下面的方法获取到根节点

 import xml.etree.ElementTree as ET
tree = ET.parse('c:\\test\\hongten.xml')
root = tree.getroot()
tag = root.tag #students

同样的我们也可以获取到根节点的属性

 attrib = root.attrib     #{}

因为根节点:students是没有属性的,所以为空。

我们要获取根节点:students的子节点名称和属性

  for child in root:
print(child.tag, child.attrib)

输出为:

student {'no' : ''}
student {'no' : ''}
student {'no' : ''}

我们同样可以获取属性对应的值

 for student in root.findall('student'):
no = student.get('no')
name = student.find('name').text
print(no, name)

输出为:

2009081097 Hongten
2009081098 DuDu
2009081099 Sum

当然,我们也可以修改XML文件的内容:

 for age in root.iter('age'):
new_age = int(age.text) + 1
age.text = str(new_age)
age.set('updated', 'yes')
tree.write('c:\\test\\hongten_update.xml')

修改后的XML文件内容如下:

 <students>
<student no="2009081097">
<name>Hongten</name>
<gender>M</gender>
<age updated="yes">21</age>
<score subject="math">97</score>
<score subject="chinese">90</score>
</student>
<student no="2009081098">
<name>DuDu</name>
<gender>W</gender>
<age updated="yes">22</age>
<score subject="math">87</score>
<score subject="chinese">96</score>
</student>
<student no="2009081099">
<name>Sum</name>
<gender>M</gender>
<age updated="yes">20</age>
<score subject="math">64</score>
<score subject="chinese">98</score>
</student>
</students>

==================================================================

以下是我对xml.etree.ElementTree模块进行了一些封装

==================================================================

 # -*- coding: utf-8 -*-
#python xml.etree.ElementTree #Author : Hongten
#Mailto : hongtenzone@foxmail.com
#Blog : http://www.cnblogs.com/hongten
#QQ : 648719819
#Version : 1.0
#Create : 2013-09-03 import os
import xml.etree.ElementTree as ET '''
在python中,解析XML文件有很多中方法
本文中要使用的方法是:xml.etree.ElementTree
'''
#global var
#show log
SHOW_LOG = True
#XML file
XML_PATH = None def get_root(path):
'''parse the XML file,and get the tree of the XML file
finally,return the root element of the tree.
if the XML file dose not exist,then print the information'''
if os.path.exists(path):
if SHOW_LOG:
print('start to parse the file : [{}]'.format(path))
tree = ET.parse(path)
return tree.getroot()
else:
print('the path [{}] dose not exist!'.format(path)) def get_element_tag(element):
'''return the element tag if the element is not None.'''
if element is not None:
if SHOW_LOG:
print('begin to handle the element : [{}]'.format(element))
return element.tag
else:
print('the element is None!') def get_element_attrib(element):
'''return the element attrib if the element is not None.'''
if element is not None:
if SHOW_LOG:
print('begin to handle the element : [{}]'.format(element))
return element.attrib
else:
print('the element is None!') def get_element_text(element):
'''return the text of the element.'''
if element is not None:
return element.text
else:
print('the element is None!') def get_element_children(element):
'''return the element children if the element is not None.'''
if element is not None:
if SHOW_LOG:
print('begin to handle the element : [{}]'.format(element))
return [c for c in element]
else:
print('the element is None!') def get_elements_tag(elements):
'''return the list of tags of element's tag'''
if elements is not None:
tags = []
for e in elements:
tags.append(e.tag)
return tags
else:
print('the elements is None!') def get_elements_attrib(elements):
'''return the list of attribs of element's attrib'''
if elements is not None:
attribs = []
for a in elements:
attribs.append(a.attrib)
return attribs
else:
print('the elements is None!') def get_elements_text(elements):
'''return the dict of element'''
if elements is not None:
text = []
for t in elements:
text.append(t.text)
return dict(zip(get_elements_tag(elements), text))
else:
print('the elements is None!') def init():
global SHOW_LOG
SHOW_LOG = True
global XML_PATH
XML_PATH = 'c:\\test\\hongten.xml' def main():
init()
#root
root = get_root(XML_PATH)
root_tag = get_element_tag(root)
print(root_tag)
root_attrib = get_element_attrib(root)
print(root_attrib)
#children
children = get_element_children(root)
print(children)
children_tags = get_elements_tag(children)
print(children_tags)
children_attribs = get_elements_attrib(children)
print(children_attribs) print('#' * 50)
#获取二级元素的每一个子节点的名称和值
for c in children:
c_children = get_element_children(c)
dict_text = get_elements_text(c_children)
print(dict_text) if __name__ == '__main__':
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 : [<Element 'students' at 0x0215C5A0>]
students
begin to handle the element : [<Element 'students' at 0x0215C5A0>]
{}
begin to handle the element : [<Element 'students' at 0x0215C5A0>]
[<Element 'student' at 0x0215C600>, <Element 'student' at 0x0215C750>, <Element 'student' at 0x0215C870>]
['student', 'student', 'student']
[{'no': ''}, {'no': ''}, {'no': ''}]
##################################################
begin to handle the element : [<Element 'student' at 0x0215C600>]
{'score': '', 'gender': 'M', 'name': 'Hongten', 'age': ''}
begin to handle the element : [<Element 'student' at 0x0215C750>]
{'score': '', 'gender': 'W', 'name': 'DuDu', 'age': ''}
begin to handle the element : [<Element 'student' at 0x0215C870>]
{'score': '', 'gender': 'M', 'name': 'Sum', 'age': ''}
>>>

========================================================

More reading,and english is important.

I'm Hongten

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

大哥哥大姐姐,觉得有用打赏点哦!多多少少没关系,一分也是对我的支持和鼓励。谢谢。
Hongten博客排名在100名以内。粉丝过千。
Hongten出品,必是精品。

E | hongtenzone@foxmail.com  B | http://www.cnblogs.com/hongten

========================================================

上一篇:**python中列表 元组 字典 集合


下一篇:Python 基础-python-列表-元组-字典-集合