python通过ElementTree操作XML
作者:大CC 时间:2021-01-09 09:12:20
1.引入库
需要用到3个类,ElementTree,Element以及建立子类的包装类SubElement
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement as SE
2.读入并解析
tree = ElementTree(file=xmlfile)
root = tree.getroot()
读入后,tree是ElementTree的类型,获取xml根结点使用getroot()方法;
XML示例文件:
<item sid='1712' name='大CC' >
<a id=1></a>
<a id=2></a>
</item>
3.获取子结点
查找Element的所有子结点:
AArry = item.findall('a')
也可使用getchildren():
childs = item.getchildren()
for subItem in childs:
print subItem.get('id')
4.插入子结点
方法一:
item = Element("item", {'sid' : '1713', 'name' : 'ityouhui'})
root.append(item)
方法二:
SE(root,'item',{'sid':'1713','name':'ityouhui'})
方法一的好处是插入之后可以对item继续操作。方法二是写法上简单,其中SE就是SubElement,在引入处做了声明;
5.操作属性
获取Element的某个属性值(eg:获取item的 name)
print root.find('item/name').text
print item.get('name')
获取Element所有属性
print item.items() # [('sid', '1712'), ('name', '大CC')]
print item.attrib # {'sid': '1712', 'name': '大CC'}
6.美化XML
在写入之前,传入root调用此函数,写入的XML文件格式整齐美观:
indent(root)
book.write(xmlfile,'utf-8')
## Get pretty look
def indent( elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
for e in elem:
indent(e, level+1)
if not e.tail or not e.tail.strip():
e.tail = i
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
return elem
来源:https://www.cnblogs.com/me115/archive/2011/10/03/2198595.html
标签:python,ElementTree,操作,XML
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3 tkinter 实现文件读取及保存功能
2023-10-24 19:45:46
![](https://img.aspxhome.com/file/2023/1/123491_0s.png)
PHP中最低级别的错误类型总结
2023-09-04 16:46:17
四种方法在SQL Server数据库中成批导入数据
2009-02-19 17:25:00
Python 中如何写注释
2022-07-10 21:53:11
python矩阵运算,转置,逆运算,共轭矩阵实例
2021-09-16 17:45:22
python爬虫学习笔记之Beautifulsoup模块用法详解
2022-06-27 12:30:03
![](https://img.aspxhome.com/file/2023/2/97122_0s.png)
Python中使用ctypes调用C++的方法
2021-09-28 10:36:13
Keras—embedding嵌入层的用法详解
2021-06-05 01:08:17
![](https://img.aspxhome.com/file/2023/9/128529_0s.jpg)
Python实现自定义读写分离代码实例
2023-04-19 14:34:57
Cython编译python为so 代码加密示例
2023-01-22 13:16:48
python 如何读、写、解析CSV文件
2022-09-21 13:59:33
![](https://img.aspxhome.com/file/2023/7/97627_0s.jpg)
python 随机森林算法及其优化详解
2023-03-30 20:20:45
Python+Tkinter制作专属图形化界面
2022-10-26 23:31:19
![](https://img.aspxhome.com/file/2023/0/68850_0s.png)
基于python元祖与字典与集合的粗浅认识
2023-11-11 07:19:48
python获取array中指定元素的示例
2021-09-11 15:37:43
css行高:line-height属性详解
2008-06-24 11:42:00
![](https://img.aspxhome.com/file/UploadPic/20086/24/2008624115434297s.gif)
python 函数定位参数+关键字参数+inspect模块
2023-07-05 23:04:37
python算法与数据结构之单链表的实现代码
2022-09-30 14:35:39
![](https://img.aspxhome.com/file/2023/0/98820_0s.png)
【总结】ASP如何获取访客真实的IP地址
2007-08-15 13:43:00
PHP PDOStatement::setAttribute讲解
2023-06-04 02:48:47