导读 这篇文章主要介绍了python实现修改xml文件内容,XML 指可扩展标记语言,是一种标记语言,是从标准通用标记语言(SGML)中简化修改出来的

XML 被设计用来传输和存储数据。

HTML 被设计用来显示数据。

XML 指可扩展标记语言(eXtensible Markup Language)。

可扩展标记语言(英语:Extensible Markup Language,简称:XML)是一种标记语言,是从标准通用标记语言(SGML)中简化修改出来的。它主要用到的有可扩展标记语言、可扩展样式语言(XSL)、XBRL和XPath等。

直接上代码,拿来就可用。

首先需要准备一个测试​​xml​​​文件,我这个文件名字为​​text.xml​​;

< data>
< country name="Liechtenstein">
< rank>yunweijia< /rank>
< year>2022< /year>
< gdppc>141100< /gdppc>
< neighbor name="Austria" direction="E" />
< neighbor name="Switzerland" direction="W" />
< /country>
< country name="Singapore">
< rank>yunweijia< /rank>
< year>2023< /year>
< gdppc>59900< /gdppc>
< neighbor name="Malaysia" direction="N" />
< /country>
< country name="Panama">
< rank>yunweijia< /rank>
< year>2024< /year>
< gdppc>13600< /gdppc>
< neighbor name="Costa Rica" direction="W" />
< neighbor name="Colombia" direction="E" />
< /country>
< /data>

然后使用以下代码来进行修改;

import xml.etree.ElementTree as ET
def change_one_xml(xml_path, xml_dw, update_content):
# 打开xml文档
doc = ET.parse(xml_path)
root = doc.getroot()
# 查找修改路劲
sub1 = root.find(xml_dw)
# 修改标签内容
sub1.text = update_content
# 保存修改
doc.write(xml_path)
 
# 欲修改文件
xml_path = r'test.xml'
 
# 修改文件中的xpath定位
xml_dw = './/country[@name="Singapore"]/year'
 
# 想要修改成什么内容
update_content = '9999'
change_one_xml(xml_path, xml_dw, update_content)

运行完毕之后,我们可以看到源文件内容变成了;

< data>
< country name="Liechtenstein">
< rank>yunweijia< /rank>
< year>2022< /year>
< gdppc>141100< /gdppc>
< neighbor name="Austria" direction="E" />
< neighbor name="Switzerland" direction="W" />
< /country>
< country name="Singapore">
< rank>yunweijia< /rank>
< year>9999< /year>
< gdppc>59900< /gdppc>
< neighbor name="Malaysia" direction="N" />
< /country>
< country name="Panama">
< rank>yunweijia< /rank>
< year>2024< /year>
< gdppc>13600< /gdppc>
< neighbor name="Costa Rica" direction="W" />
< neighbor name="Colombia" direction="E" />
< /country>
< /data>

到此这篇关于python实现修改xml文件内容的文章就介绍到这了

原文来自:https://www.jb51.net/article/256845.htm

本文地址:https://www.linuxprobe.com/python-xml-linux.html编辑:倪家兴,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/