您的位置:首頁/技術文章
文章詳情頁

python對XML文件的操作實現代碼

瀏覽:103日期:2022-08-01 08:28:12

python對XML文件的操作

1、xml 創建

import xml.etree.ElementTree as ETnew_xml=ET.Element(’personinfolist’) #最外面的標簽名personinfo=ET.SubElement(new_xml,’personinfo’,attrib={’enrolled’:’aaa’}) #對應的參數是:父級標簽是誰,當前標簽名,當前標簽屬性與值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 數據查詢

import xml.etree.ElementTree as ETtree=ET.parse(’text1.xml’)root=tree.getroot()print(root.tag)#遍歷 xml 文檔for i in root: print(i.tag,i.attrib) # tag是指標簽名,attrib 是指標簽里的屬性,text 是指標簽內容 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 數據修改

import xml.etree.ElementTree as ETtree=ET.parse(’text1.xml’)root=tree.getroot()print(root.tag)#修改 xmlfor node in root.iter(’year’): #要修改的標簽 new_year=int(node.text)+1 node.text=str(new_year) node.set(’updsted_by’,’kong’) #給這個標簽(year)添加新的屬性 key:valuetree.write(’text1.xml’) #再吧數據寫回去

4、xml 數據刪除

import xml.etree.ElementTree as ETtree=ET.parse(’text1.xml’)root=tree.getroot()for country in root.findall(’country’): #會取這個標簽所有的數據 rank=int(country.find(’rank’).text) if rank > 50: root.remove(country) #刪除數據tree.write(’output.xml’) #再把數據寫回文件

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区