python 写xml文件
步骤:
1.通过Element 创建根节点
2.通过SubElement 添加子节点
3.通过Element创建节点,再通过append,添加子节点到节点
4.通过ElementEtree生成xml文件对像,用来生成xml文件
1 from xml.etree import ElementTree as ET 2 3 root = ET.Element('catalog') #创建首节点 4 maxid = ET.SubElement(root, 'maxid') #增加子节点 5 maxid.text = '4' 6 item = ET.SubElement(root, 'item', attrib={"id": "1"}) 7 caption = ET.SubElement(item, 'caption') 8 caption.text = 'Python' 9 10 item_2 = ET.SubElement(item, 'item', attrib={"id": "4"}) 11 caption = ET.SubElement(item_2, 'caption') 12 caption.text = '测试' 13 14 item_3 = ET.Element('item', {'id': '2'}) #创建节点 15 root.append(item_3) #追加节点到root节点下 16 caption_2 = ET.Element('caption') 17 caption_2.text='Zope' 18 item_3.append(caption_2) 19 20 w = ET.ElementTree(root) 21 w.write('wt.xml', 'utf-8', True)