Python入门:常用模块—xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

xml的格式如下,就是通过<>节点来区别数据结构的:

<data>

``<country name``=``"Liechtenstein"``>

``<rank updated``=``"yes"``>``2``<``/``rank>

``<year updated``=``"yes"``>``2010``<``/``year>

``<gdppc>``141100``<``/``gdppc>

``<neighbor direction``=``"E" name``=``"Austria" /``>

``<neighbor direction``=``"W" name``=``"Switzerland" /``>

``<``/``country>

``<country name``=``"Singapore"``>

``<rank updated``=``"yes"``>``5``<``/``rank>

``<year updated``=``"yes"``>``2013``<``/``year>

``<gdppc>``59900``<``/``gdppc>

``<neighbor direction``=``"N" name``=``"Malaysia" /``>

``<``/``country>

``<country name``=``"Panama"``>

``<rank updated``=``"yes"``>``69``<``/``rank>

``<year updated``=``"yes"``>``2013``<``/``year>

``<gdppc>``13600``<``/``gdppc>

``<neighbor direction``=``"W" name``=``"Costa Rica" /``>

``<neighbor direction``=``"E" name``=``"Colombia" /``>

``<``/``country>

<``/``data>

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

import xml.etree.ElementTree as ET

tree ``= ET.parse(``"xmltest.xml"``)

root ``= tree.getroot()

print``(root.tag)

# 遍历xml文档

for child ``in root:

``print``(child.tag, child.attrib)

``for i ``in child:

``print``(i.tag, i.text)

# 遍历year节点

for node ``in root.``iter``(``'year'``):

``print``(node.tag, node.text)

# 修改和删除xml文档内容

# 修改

for node ``in root.``iter``(``'year'``):

``new_year ``= int``(node.text) ``+ 1

``node.text ``= str``(new_year)

``node.``set``(``'updated'``, ``'yes'``)

tree.write(``"xmltest.xml"``)

# 删除

for country ``in root.findall(``'country'``):

``rank ``= int``(country.find(``'rank'``).text)

``if rank > ``50``:

``root.remove(country)

tree.write(``'output.xml'``)

自己创建xml文档

new_xml ``= ET.Element(``"namelist"``)

name ``= ET.SubElement(new_xml, ``"name"``, attrib``=``{``"enrolled"``: ``"yes"``})

age ``= ET.SubElement(name, ``"age"``, attrib``=``{``"checked"``: ``"no"``})

sex ``= ET.SubElement(name, ``"sex"``)

sex.text ``= '33'

name2 ``= ET.SubElement(new_xml, ``"name"``, attrib``=``{``"enrolled"``: ``"no"``})

age ``= ET.SubElement(name2, ``"age"``)

age.text ``= '19'

et ``= ET.ElementTree(new_xml) ``# 生成文档对象

et.write(``"test.xml"``, encoding``=``"utf-8"``, xml_declaration``=``True``)

ET.dump(new_xml) ``# 打印生成的格式

相关推荐
写代码的【黑咖啡】27 分钟前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
抠头专注python环境配置30 分钟前
解决Windows安装PythonOCC报错:从“No module named ‘OCC’ ”到一键成功
人工智能·windows·python·3d·cad·pythonocc
华研前沿标杆游学34 分钟前
2026年华研就业实践营|走进字节跳动,解锁科技行业职业新航向
python
啊阿狸不会拉杆1 小时前
《数字图像处理》第 4 章 - 频域滤波
开发语言·python·数字信号处理·数字图像处理·频率域滤波
HarmonLTS1 小时前
Pygame动画制作进阶(可直接运行,附核心原理)
python·pygame
他们叫我技术总监1 小时前
Python 列表、集合、字典核心区别
android·java·python
悟能不能悟1 小时前
前端上载文件时,上载多个文件,但是一个一个调用接口,怎么实现
前端
木卫四科技1 小时前
Chonkie 技术深度学习
人工智能·python·rag
Omigeq2 小时前
1.2.1 - 图搜索算法(以A*为例) - Python运动规划库教程(Python Motion Planning)
开发语言·python·机器人·图搜索算法
资深流水灯工程师2 小时前
基于Python的Qt开发之Pyside6 串口接收数据被分割的解决方案
开发语言·python·qt