查看
f = ET.parse('xmltest') #解析root = f.getroot() #root为根节点print(root.tag) #tag 标签#遍历xml文档for child in root: print(child.tag,child.attrib) #.attrib归属,属性 for i in child: print('\t',i.tag,i.attrib,i.text)#只遍历year 节点for node in root.iter('year'): #.iter 方法 print(node.tag,node.text) #.text .tag
修改和删除xml文档内容
import xml.etree.ElementTree as ETf = ET.parse('xmltest')root = f.getroot()#修改for node in root.iter('year'): #.iter new_year = int(node.text)+1 node.text = str(new_year) #.text node.set("updated","yes") #.set 增加属性f.write("xmltest2")#删除nodefor country in root.findall('country'): #.findall rank = int(country.find('rank').text) #.find if rank > 50: root.remove(country) #.removef.write('output.xml')
创建xml文档
import xml.etree.ElementTree as ETroot = ET.Element("namelist")name = ET.SubElement(root,'name',attrib={"enrolled":"yes"})age = ET.SubElement(name,"age",attrib={"checked":"no"})sex = ET.SubElement(name,'sex')sex.text = '33'name2 = ET.SubElement(root,'name2',attrib={"enrolled":"no"})age = ET.SubElement(name,"age")age.text = '19'et = ET.ElementTree(root) #生成文档对象et.write("xmltest3.xml", encoding="utf-8",xml_declaration=True)ET.dump(root) #打印生成的格式