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 ETdef 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文件內容得內容就介紹到這了,更多相關python修改xml文件內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。