# -*- coding:UTF-8 -*-
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
#获取根节点
def getRoot(xmlpath):
'''
xmlpath:xml文件的路径
'''
root = ET.parse(xmlpath).getroot()
return root
#格式化输出xml文件
def display(root):
rough_string = ET.tostring(root, 'utf-8')
reparsed = minidom.parseString(rough_string)
print reparsed.toprettyxml(indent=" " , encoding="utf-8");
if __name__ == '__main__':
root = ET.Element('bookList')
#==============添加节点========================
#向root节点下插入节点<book id='ISO001'>
bookE = ET.SubElement(root,'book')#方式一
bookE.set('id', 'ISO001')#为节点添加属性
#向<book>节点下插入<author>Gaosilin</version>节点
authorE = ET.Element('author')
authorE.text = 'Gaosilin'#为节点赋值
bookE.append(authorE)#方式二
##向<book>节点下插入<name>Java</name>节点
nameE = ET.Element('name')
nameE.text = 'java'
bookE.insert(1,nameE)#方式三
#修改
nameE.text = '修改后的C'
display(root)
#==============删除节点========================
bookE.remove(nameE)#注意需删除的节点一定要是该父节点的下一级节点
bookE.remove(authorE)
bookE.clear()#删除该节点下的所有子节点,等价于上两句
root.remove(bookE)
# root.remove(nameE)#出错:因为nameE的上一级节点是bookE而不是root
display(root)
|