溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python:xml模塊用法-xml處理、修改、刪除

發(fā)布時(shí)間:2020-06-21 05:55:09 來源:網(wǎng)絡(luò) 閱讀:3096 作者:luckercai 欄目:編程語言

xmltest.xml內(nèi)容如下:
<data>
<country name="Liechten">
<rank updated="yes">1</rank>
<year updated_by="Alex">2017</year>
<gdppc>140000</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
</data>



xml處理:
import xml.tree.ElementTree as ET

tree=ET.parse("xmltest.xml")
root=tree.getroot() #獲取根節(jié)點(diǎn)
print(root)
print(root.tag)

#遍歷xml
for child in root:
......print(child.tag,child.attrib) #打印孩子節(jié)點(diǎn)標(biāo)簽和屬性
......for i in child:
............print(i.tag,i.text.i.attrib)

#只遍歷year節(jié)點(diǎn)
for node in root.iter('year')
......print(node.tag,node.text)



#xml修改

for node in root.iter('year'):
......new_year=int(node.text)
......node.text=str(new_year)
......node.set("updated_by","cai")
tree.write("xmltest.xml")



#刪除
for country in root.findall('country'):
......rank=int(country.find('rank').text)
......if rank>50:
..........root.remove(country)
tree.write('output.xml')



#自己編寫
import xml.etree.ElementTree as ET

new_xml=ET.Element("personinfolist")
personinfo=ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"yes"})
name=ET.SubElement(personinfo,"name")
name.text="huaha"
age=ET.SubElement(personinfo,"age",attrib={"checked":"no"})
age.text='12'

et=ET.ElementTree(new_xml) #生成文檔對象
et.write("test.xml",encoding='utf-8',xml_declaration=True)
ET.dump(new_xml) #打印生成的格式

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI