python--模块学习之xml模块
2024-09-04 08:35:19
xml即可扩展标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。
本文主要学习的ElementTree是python的XML处理模块,它提供了一个轻量级的对象模型。在使用ElementTree模块时,需要import xml.etree.ElementTree的操作。ElementTree表示整个XML节点树,而Element表示节点数中的一个单独的节点。
XML示例一:使用XML读取本地的first.xml文件,并解析数据
以下是first.xml文件的内容
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>14110</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="switzeriand"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia"/>
</country>
<country name="Faname">
<rank updated="yes">69</rank>
<year>2019</year>
<gdppc>13360</gdppc>
<neighbor direction="W" name="Costa Rica"/>
<neighbor direction="E" name="Colombia"/>
</country>
</data>
python代码实现:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
使用XML读取本地的first.xml文件,并解析数据
"""
from xml.etree import ElementTree as ET root = ET.XML(open("first.xml", "r", encoding='utf-8').read()) #读取本地的first.xml文件,解析字符串 #通过循环读取子节点的内容
for node in root:
print(node.tag, node.attrib, node.find("year").text)
python实现读取first.xml文件并解析的结果:
XML示例二:通过.parse()方式打开文件,可以实现修改文件内容
#!/usr/bin/env python
# -*- coding:utf-8 -*- #打开并解析文件内容
from xml.etree import ElementTree as ET tree = ET.parse("first.xml")
root = tree.getroot() #通过.getroot()获取根节点
for node in root.iter('year'): #通过.iter()迭代找到指定的子节点
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('name', 'YY') #通过.set()给year节点添加一个Name属性
#del node.attrib['name'] 通过.attrib[]可删除指定的属性
head = root.find('gdppc') # 获取节点
root.remove(head) # 删除节点 #通过.write()将修改的内容从内存中写入文件
tree.write("first.xml")
示例三:创建xml文档
#!/usr/bin/env python
# -*- coding:utf-8 -*- from xml.etree import ElementTree as ET #创建根节点
new_xml = ET.Element("namelist") #在根节点下创建子节点1
name1 = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
#在name1子节点下再创建孙节点
age1 = ET.SubElement(name1, "age", attrib={"checked": "no"})
sex1 = ET.SubElement(name1, "sex")
sex1.text = '' #在根节点下创建子节点2
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age2 = ET.SubElement(name2, "age")
age2.text = '' #生成文档对象
et = ET.ElementTree(new_xml)
et.write("new_xml.xml", encoding='utf-8', xml_declaration=True)
创建xml文档实现的结果:
最新文章
- nfs 笔记 2
- RMAN冷备份异机还原
- UWP消息通知
- ORACLE常用SQL优化hint语句
- C#中动态读写App.config配置文件
- excel上传与下载
- hdoj 1859 最小长方形
- Java虚拟机--虚拟机编译器
- JSON解析---初识
- 理论篇:关注点分离(Separation of concerns, SoC)
- 省市县从数据库读出来的list数据转换成json格式的数据
- pyqt5实现注册界面并获得文本框内容
- VS.NET C# 开发ArcGis插件无法进入断点调试的解决方法
- Python_多进程
- [HTML]HTML隐藏文本框的四种方式
- Markdown基础教程
- Mac 创建证书(以 创建gdb证书 为例 )
- 2016 ACM/ICPC Asia Regional Qingdao Online 1001 I Count Two Three(打表+二分搜索)
- poj1511
- unbind() 移除事件内处理方法