學習筆記-模塊之xml文件處理
阿新 • • 發佈:2018-04-30
info font 處理xml node 節點 family 對象 find upd
處理XML文檔
遍歷xml文檔
1 #遍歷xml文檔的子標簽 2 for child in root: 3 print(child.tag,child.attrib) 4 #子標簽名 屬性 5 for i in child: 6 print(i.tag,i.text) 7 #子標簽名 屬性 8 #字節數標簽不能遍歷出屬性,輸出為空 9 #改進 10 print(i.tag,i.text,i.attrib) 11 12 #遍歷自己需要的 例如只遍歷‘year‘節點 13 for node in root.iter(‘year‘): 14 print(node.tag,node.text)
修改
1 import xml.etree.ElementTree as ET 2 3 tree=ET.parse(‘xml_test.xml‘) 4 root=tree.getroot() 5 6 for node in root.iter(‘year‘): 7 new_year=int(node.text)+1 8 node.text=str(new_year) 9 #賦值 10 node.set(‘updated‘,‘yes‘) 11 給year標簽增加屬性 12 13 tree.write(‘xml_test.xml‘)
刪除node
1 tree=ET.parse(‘xml_test.xml‘) 2 root=tree.getroot() 3 4 for country in root.findall(‘country‘): #遍歷country 5 rank = int(country.find(‘rank‘).text) #找出rank 6 if rank > 50: 7 root.remove(country)8 9 tree.write(‘output.xml‘) #寫入文件為output.xml文件中
新建xml文件
1 import xml.etree.ElementTree as ET 2 3 new_xml = ET.Element("personinfolist") #創建根節點 4 personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"}) 5 #是new_xml的子節點 6 name = ET.SubElement(personinfo, "name") 7 name.text=‘Jeck‘ 8 age = ET.SubElement(personinfo, "age", attrib={"checked": "no"}) 9 #是personnifo的子節點 10 sex = ET.SubElement(personinfo, "sex") 11 sex.text=‘Men‘ 12 age.text = ‘33‘ #給age節點賦值 13 personinfo2 = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "no"}) 14 name = ET.SubElement(personinfo2, "name") 15 name.text=‘Ailice‘ 16 age = ET.SubElement(personinfo2, "age") 17 age.text = ‘19‘ 18 19 et = ET.ElementTree(new_xml) # 生成文檔對象 20 et.write("test.xml", encoding="utf-8", xml_declaration=True) 21 #寫入到test.xml文件中 聲明是xml格式的 22 23 ET.dump(new_xml) # 打印生成的格式
學習筆記-模塊之xml文件處理