python實現(xiàn)修改xml文件內(nèi)容
XML 被設(shè)計用來傳輸和存儲數(shù)據(jù)。
HTML 被設(shè)計用來顯示數(shù)據(jù)。
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) # 修改標簽內(nèi)容 sub1.text = update_content # 保存修改 doc.write(xml_path) # 欲修改文件 xml_path = r'test.xml' # 修改文件中的xpath定位 xml_dw = './/country[@name="Singapore"]/year' # 想要修改成什么內(nèi)容 update_content = '9999' change_one_xml(xml_path, xml_dw, update_content)
運行完畢之后,我們可以看到源文件內(nèi)容變成了;
<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>
到此這篇關(guān)于python實現(xiàn)修改xml文件內(nèi)容的文章就介紹到這了,更多相關(guān)python修改xml文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的內(nèi)置數(shù)據(jù)類型中的數(shù)字
這篇文章主要介紹Python內(nèi)置數(shù)據(jù)類型中的數(shù)字(Number),包括整數(shù)(int),小數(shù)(float),復(fù)數(shù)(Complex),布爾類型(bool)這幾種數(shù)據(jù)類型。本文介紹的都是Python3.x中的數(shù)據(jù)類型,需要的朋友請參考下面文章2021-09-09
使用python爬取連續(xù)降水數(shù)據(jù)信息實例
這篇文章主要為大家介紹了使用python提取連續(xù)降水數(shù)據(jù)信息實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
pandas?數(shù)據(jù)透視和逆透視的實現(xiàn)
本文介紹了pandas?數(shù)據(jù)透視和逆透視的實現(xiàn),包含pivot()方法透視及pivot_table()方法逆透視,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
TensorFlow實現(xiàn)非線性支持向量機的實現(xiàn)方法
本篇文章主要介紹了TensorFlow實現(xiàn)非線性支持向量機的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
9行Python3代碼實現(xiàn)批量提取PDF文件的指定內(nèi)容
這篇文章主要為大家詳細介紹了如何通過9行Python3代碼實現(xiàn)批量提取PDF文件的指定內(nèi)容,文中的示例代碼講解詳細,感興趣的小伙伴可以嘗試一下2022-12-12
Python格式化輸出字符串方法小結(jié)【%與format】
這篇文章主要介紹了Python格式化輸出字符串方法,結(jié)合實例形式總結(jié)分析了使用%與format函數(shù)進行字符串格式化操作相關(guān)實現(xiàn)技巧與注意事項,需要的朋友可以參考下2018-10-10

