import xml.etree.ElementTree as ET # 生成XML new_xml = ET.Element('note') name = ET.SubElement(new_xml, 'to', attrib={'name': 'name'}) name.text = 'George' from_node = ET.SubElement(new_xml, 'from') from_node.text = 'John' heading = ET.SubElement(new_xml, 'heading') heading.text = 'Reminder' body = ET.SubElement(new_xml, 'body') body.text = "Don't forget the meeting!" # 生成XML文件 ET = ET.ElementTree(new_xml) ET.write('xml_test.xml', encoding='utf-8', xml_declaration=True) # 读取xml文件内容 tree = ET.parse('xml_test.xml') root = tree.getroot() print(root) # <Element 'note' at 0x02E69090> print(root.tag) # note 标签名 # 获取指定标签 for i in root.iter('from'): print('标签名--》', i.tag) # 标签名 print('标属性--》', i.attrib) # 标签属性 print('标内容--》', i.text) # 标签内容 # 修改 for i in root.iter('from'): i.text = i.text + '_new' # 修改内容 i.set('updated', 'yes') # 修改属性 # findall 查找全部标签 find 查找一个标签 for heading in root.findall('heading'): print(heading.tag) # 删除标签 root.remove(heading) tree.write('xml_new.xml') # 写入处理后的xml到文件