python ElementTree 基本读操作示例
时间:2022-10-23 07:27:25
示例可以附件中下载
1.加载xml文件
加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件
2.获取element的方法
a) 通过getiterator
b) 过 getchildren
c) find方法
d) findall方法
示例如下:
#-*- coding:utf-8 -*-
from xml.etree import ElementTree
def print_node(node):
'''''打印结点基本信息'''
print "=============================================="
print "node.attrib:%s" % node.attrib
if node.attrib.has_key("age") > 0 :
print "node.attrib['age']:%s" % node.attrib['age']
print "node.tag:%s" % node.tag
print "node.text:%s" % node.text
def read_xml(text):
'''''读xml文件'''
# 加载XML文件(2种方法,一是加载指定字符串,二是加载指定文件)
# root = ElementTree.parse(r"D:\test.xml")
root = ElementTree.fromstring(text)
# 获取element的方法
# 1 通过getiterator
lst_node = root.getiterator("person")
for node in lst_node:
print_node(node)
# 2通过 getchildren
lst_node_child = lst_node[0].getchildren()[0]
print_node(lst_node_child)
# 3 .find方法
node_find = root.find('person')
print_node(node_find)
#4. findall方法
node_findall = root.findall("person/name")[1]
print_node(node_findall)
if __name__ == '__main__':
# read_xml(open("test.xml").read())
write_xml(open("test.xml").read())
标签:python,ElementTree
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用网际数据库浏览器在线维护Access数据库
2008-05-23 13:05:00
mysql利用参数sql_safe_updates限制update/delete范围详解
2024-01-27 06:52:53
Go语言的队列和堆栈实现方法
2024-05-09 09:40:13
php查找指定目录下指定大小文件的方法
2023-09-03 17:53:36
Python 异步如何使用等待有时间限制协程
2022-02-12 09:29:28
从pandas一个单元格的字符串中提取字符串方式
2022-10-14 21:24:35
Python + selenium 自动化测试框架详解
2021-01-15 00:06:35
![](https://img.aspxhome.com/file/2023/7/112947_0s.png)
python数字类型和占位符详情
2022-10-03 06:36:32
解决asp中ADODB.Stream 0x800A0C93 错误
2008-01-08 19:28:00
Python3 中文文件读写方法
2021-07-14 20:02:39
[翻译]标记语言和样式手册 chapter 5 表单
2008-01-23 17:20:00
![](https://img.aspxhome.com/file/UploadPic/20081/23/2008123183735445s.jpg)
Jupyter notebook无法导入第三方模块的解决方式
2023-05-23 08:28:53
![](https://img.aspxhome.com/file/2023/1/72791_0s.jpg)
jquery加载页面的方法(页面加载完成就执行)
2024-04-23 09:10:11
浅析Mysql和Oracle分页的区别
2024-01-23 16:38:49
![](https://img.aspxhome.com/file/2023/6/67026_0s.png)
Python使用Scrapy保存控制台信息到文本解析
2022-04-12 20:29:00
![](https://img.aspxhome.com/file/2023/9/97059_0s.jpg)
Python制作爬虫抓取美女图
2021-05-15 12:47:45
![](https://img.aspxhome.com/file/2023/9/120399_0s.jpg)
python数据可视化matplotlib绘制折线图示例
2023-05-20 23:01:56
![](https://img.aspxhome.com/file/2023/9/103159_0s.png)
人工智能学习PyTorch教程之层和块
2021-12-05 09:36:15
![](https://img.aspxhome.com/file/2023/6/120376_0s.png)
PPOCRLabel标注的txt格式如何转换成labelme能修改的json格式
2021-08-31 06:01:45
![](https://img.aspxhome.com/file/2023/7/107087_0s.jpg)
python神经网络Batch Normalization底层原理详解
2021-01-28 12:50:08
![](https://img.aspxhome.com/file/2023/2/75292_0s.png)