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) ``# 打印生成的格式

相关推荐
空中湖5 分钟前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
镜子AI44 分钟前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft
欣欣之王来了2 小时前
原始HTML插值:v-html指令的使用与安全风险
前端·学习·架构·项目·vue3教程
小oo呆2 小时前
【学习心得】Python协程
python
IT_陈寒2 小时前
Redis的LRU淘汰策略坑了我一整天
前端·人工智能·后端
计算机魔术师2 小时前
砍半价格、参数再涨,国产旗舰追到 Opus 鼻尖了
前端
信誓旦旦的程序猿2 小时前
【Python量化实战宝典 #22】涨跌停、连板情绪手册:情绪指标构建(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
特立独行的猫A2 小时前
10 MB 的桌面 AI 客户端:用仓颉 + 系统 WebView 替代 Electron
前端·harmonyos
gCode Teacher 格码致知2 小时前
Pandas教学-21:subplots的使用
python·pandas·1024程序员节
2601_967980112 小时前
Python开发的顶级开源项目全景图:2025-2026年生态概览
python·机器学习·开源项目·数据科学·生态概览