python對XML文件的操作實(shí)現(xiàn)代碼
python對XML文件的操作
1、xml 創(chuàng)建
import xml.etree.ElementTree as ETnew_xml=ET.Element(’personinfolist’) #最外面的標(biāo)簽名personinfo=ET.SubElement(new_xml,’personinfo’,attrib={’enrolled’:’aaa’}) #對應(yīng)的參數(shù)是:父級標(biāo)簽是誰,當(dāng)前標(biāo)簽名,當(dāng)前標(biāo)簽屬性與值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 ETtree=ET.parse(’text1.xml’)root=tree.getroot()print(root.tag)#遍歷 xml 文檔for i in root: print(i.tag,i.attrib) # tag是指標(biāo)簽名,attrib 是指標(biāo)簽里的屬性,text 是指標(biāo)簽內(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 標(biāo)簽for w in root.iter(’year’): #只遍歷指定標(biāo)簽 print(w.tag,w.text)
3、xml 數(shù)據(jù)修改
import xml.etree.ElementTree as ETtree=ET.parse(’text1.xml’)root=tree.getroot()print(root.tag)#修改 xmlfor node in root.iter(’year’): #要修改的標(biāo)簽 new_year=int(node.text)+1 node.text=str(new_year) node.set(’updsted_by’,’kong’) #給這個(gè)標(biāo)簽(year)添加新的屬性 key:valuetree.write(’text1.xml’) #再吧數(shù)據(jù)寫回去
4、xml 數(shù)據(jù)刪除
import xml.etree.ElementTree as ETtree=ET.parse(’text1.xml’)root=tree.getroot()for country in root.findall(’country’): #會(huì)取這個(gè)標(biāo)簽所有的數(shù)據(jù) rank=int(country.find(’rank’).text) if rank > 50: root.remove(country) #刪除數(shù)據(jù)tree.write(’output.xml’) #再把數(shù)據(jù)寫回文件
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java commons-httpclient如果實(shí)現(xiàn)get及post請求2. 一文帶你徹底理解Java序列化和反序列化3. JS中6個(gè)對象數(shù)組去重的方法4. Python基于requests庫爬取網(wǎng)站信息5. vscode運(yùn)行php報(bào)錯(cuò)php?not?found解決辦法6. python中文本字符處理的簡單方法記錄7. PHP laravel實(shí)現(xiàn)導(dǎo)出PDF功能8. Python使用Selenium自動(dòng)進(jìn)行百度搜索的實(shí)現(xiàn)9. PHP利用curl發(fā)送HTTP請求的實(shí)例代碼10. 資深程序員:給Python軟件開發(fā)測試的25個(gè)忠告!

網(wǎng)公網(wǎng)安備