python对XML文件的操作实现代码

作者:Kong-Ming 时间:2023-05-03 22:27:26 

python对XML文件的操作

1、xml 创建


import xml.etree.ElementTree as ET

new_xml=ET.Element('personinfolist')  #最外面的标签名
personinfo=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'aaa'}) #对应的参数是:父级标签是谁,当前标签名,当前标签属性与值
name=ET.SubElement(personinfo,'name')
name.text='xaoming'
age=ET.SubElement(personinfo,'age',attrib={'checked':'yes'})
age.text='23'

personinfo2=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'bbb'})
name=ET.SubElement(personinfo2,'name')
name.text='xaokong'
age=ET.SubElement(personinfo2,'age',attrib={'checked':'no'})
age.text='20'

et=ET.ElementTree(new_xml)
et.write('text1.xml',encoding='utf-8',xml_declaration=True)#生成text1.xml

2、xml 数据查询


import xml.etree.ElementTree as ET
tree=ET.parse('text1.xml')
root=tree.getroot()
print(root.tag)
#遍历 xml 文档
for i in root:
 print(i.tag,i.attrib)  # tag是指标签名,attrib 是指标签里的属性,text 是指标签内容
 for j in i:
   print(j.tag,j.attrib,j.text)
   for k in j:
     print(k.tag,k.attrib,k.text)
#只遍历 year 标签
for w in root.iter('year'): #只遍历指定标签
 print(w.tag,w.text)

3、xml 数据修改


import xml.etree.ElementTree as ET
tree=ET.parse('text1.xml')
root=tree.getroot()
print(root.tag)
#修改 xml
for node in root.iter('year'): #要修改的标签
 new_year=int(node.text)+1
 node.text=str(new_year)
 node.set('updsted_by','kong') #给这个标签(year)添加新的属性 key:value
tree.write('text1.xml')   #再吧数据写回去

4、xml 数据删除


import xml.etree.ElementTree as ET
tree=ET.parse('text1.xml')
root=tree.getroot()
for country in root.findall('country'):  #会取这个标签所有的数据
 rank=int(country.find('rank').text)
 if rank > 50:
   root.remove(country)  #删除数据
tree.write('output.xml') #再把数据写回文件

来源:https://www.cnblogs.com/km-thonder/p/12577489.html

标签:python,XML,文件,操作
0
投稿

猜你喜欢

  • Python 常用模块 re 使用方法详解

    2021-02-23 13:10:19
  • 对numpy下的轴交换transpose和swapaxes的示例解读

    2022-09-11 10:30:51
  • Mysql索引选择以及优化详解

    2024-01-18 13:56:12
  • 采用python实现简单QQ单用户机器人的方法

    2022-06-26 03:28:40
  • 如何使用python对图片进行批量压缩详解

    2022-12-05 04:22:25
  • javascript中解析四则运算表达式的算法和示例

    2024-04-28 09:41:37
  • Pycharm运行程序时,控制台输出PyDev console:starting问题

    2022-09-27 14:26:32
  • Python多线程的使用详情

    2023-05-29 15:13:36
  • MySQL 函数过程递归

    2008-07-25 19:32:00
  • 前端如何用post的方式进行eventSource请求

    2024-04-10 16:13:32
  • Python+OpenCV实现图片及视频中选定区域颜色识别

    2021-04-10 03:36:26
  • vue关于eslint空格缩进等的报错问题及解决

    2024-05-10 14:09:26
  • YUI学习笔记(2)

    2009-01-21 16:11:00
  • Pycharm导入anaconda环境的教程图解

    2022-12-15 04:26:40
  • pytorch1.0中torch.nn.Conv2d用法详解

    2023-07-17 10:53:48
  • SQL Server2022安装图文教程(最新推荐)

    2024-01-27 04:55:25
  • Python嵌入C/C++进行开发详解

    2024-01-02 06:39:48
  • python数据解析BeautifulSoup爬取三国演义章节示例

    2021-03-21 13:27:27
  • pycharm 配置svn的图文教程(手把手教你)

    2022-10-21 18:47:47
  • 以数据库字段分组显示数据的sql语句(详细介绍)

    2024-01-29 07:39:49
  • asp之家 网络编程 m.aspxhome.com