1. 程式人生 > >python:xml模塊用法-xml處理、修改、刪除

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

節點 文檔 direction ear direct and root odi pytho

xmltest.xml內容如下:
<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() #獲取根節點
print(root)
print(root.tag)

#遍歷xml
for child in root:
......print(child.tag,child.attrib) #打印孩子節點標簽和屬性
......for i in child:
............print(i.tag,i.text.i.attrib)

#只遍歷year節點
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) #打印生成的格式

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