日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python實現修改xml文件內容_python

作者:公號運維家??????? ? 更新時間: 2022-09-18 編程語言

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>

原文鏈接:https://blog.51cto.com/u_12386780/5479899

欄目分類
最近更新