python對XML文件的操作實現(xiàn)代碼
python對XML文件的操作
1、xml 創(chuàng)建
import xml.etree.ElementTree as ET new_xml=ET.Element('personinfolist') #最外面的標簽名 personinfo=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'aaa'}) #對應的參數(shù)是:父級標簽是誰,當前標簽名,當前標簽屬性與值 name=ET.SubElement(personinfo,'name') name.text='xaoming' age=ET.SubElement(personinfo,'age',attrib={'checked':'yes'}) age.text='23' personinfo2=ET.SubElement(new_xml,'personinfo',attrib={'enrolled':'bbb'}) name=ET.SubElement(personinfo2,'name') name.text='xaokong' age=ET.SubElement(personinfo2,'age',attrib={'checked':'no'}) age.text='20' et=ET.ElementTree(new_xml) et.write('text1.xml',encoding='utf-8',xml_declaration=True)#生成text1.xml
2、xml 數(shù)據(jù)查詢
import xml.etree.ElementTree as ET tree=ET.parse('text1.xml') root=tree.getroot() print(root.tag) #遍歷 xml 文檔 for i in root: print(i.tag,i.attrib) # tag是指標簽名,attrib 是指標簽里的屬性,text 是指標簽內(nèi)容 for j in i: print(j.tag,j.attrib,j.text) for k in j: print(k.tag,k.attrib,k.text) #只遍歷 year 標簽 for w in root.iter('year'): #只遍歷指定標簽 print(w.tag,w.text)
3、xml 數(shù)據(jù)修改
import xml.etree.ElementTree as ET tree=ET.parse('text1.xml') root=tree.getroot() print(root.tag) #修改 xml for node in root.iter('year'): #要修改的標簽 new_year=int(node.text)+1 node.text=str(new_year) node.set('updsted_by','kong') #給這個標簽(year)添加新的屬性 key:value tree.write('text1.xml') #再吧數(shù)據(jù)寫回去
4、xml 數(shù)據(jù)刪除
import xml.etree.ElementTree as ET tree=ET.parse('text1.xml') root=tree.getroot() for country in root.findall('country'): #會取這個標簽所有的數(shù)據(jù) rank=int(country.find('rank').text) if rank > 50: root.remove(country) #刪除數(shù)據(jù) tree.write('output.xml') #再把數(shù)據(jù)寫回文件
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)的線性回歸算法示例【附csv文件下載】
這篇文章主要介紹了Python實現(xiàn)的線性回歸算法,涉及Python使用最小二乘法、梯度下降算法實現(xiàn)線性回歸相關(guān)算法操作與使用技巧,需要的朋友可以參考下2018-12-12解決python3 HTMLTestRunner測試報告中文亂碼的問題
今天小編就為大家分享一篇解決python3 HTMLTestRunner測試報告中文亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python中將數(shù)據(jù)生成為Excel文件的5種方法舉例
工作中需要把數(shù)據(jù)導入到excel中,記錄一下操作方式,這篇文章主要給大家介紹了關(guān)于python中將數(shù)據(jù)生成為Excel文件的5種方法,文中通過圖文以及代碼介紹的非常詳細,需要的朋友可以參考下2023-10-10解決pycharm運行程序出現(xiàn)卡住scanning files to index索引的問題
今天小編就為大家分享一篇解決pycharm運行程序出現(xiàn)卡住scanning files to index索引的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python函數(shù)參數(shù)分類使用與新特性詳細分析講解
在聲明函數(shù)的時候,一般會根據(jù)函數(shù)所要實現(xiàn)的功能來決定函數(shù)是否需要參數(shù)。在多數(shù)情況下,我們聲明的函數(shù)都會使用到參數(shù),這篇文章主要介紹了Python函數(shù)參數(shù)2023-01-01Python數(shù)據(jù)類型之String字符串實例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之String字符串,結(jié)合實例形式詳細講解了Python字符串的概念、定義、連接、格式化、轉(zhuǎn)換、查找、截取、判斷等常見操作技巧,需要的朋友可以參考下2019-05-05django實現(xiàn)模板中的字符串文字和自動轉(zhuǎn)義
這篇文章主要介紹了django實現(xiàn)模板中的字符串文字和自動轉(zhuǎn)義,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03