整理一下在个人使用的一些有关的minidom操作xml的命令,备查
读取xml文件
1、引入minidom类
from xml.dom import minidom
2、获取xml文件并得到文档元素对象
path=minidom.parse('文件名称')
root=path.documentElement
3、通过元素名字的获取子元素
itemlist=root.getElementsByTagName('元素名称')
4、若元素存在属性,获取元素属性
item = itemlist[0]
item.getAttribute(‘属性名称’)
5、获取元素下的值(处理元素值中空格、回车等)
content=itemlist[0].childNodes[0].nodeValue
content="".join(content.split())
写入xml文件
1、打开要写入的xml文件
f=open("student.xml","w")
2、创建根节点及子节点、子节点内容
doc=minidom.Document()
infoNode=doc.createElement("info")
doc.appendChild(infoNode)
建立子节点并加入名称
nameNode=doc.createElement("name")
infoNode.appendChild(nameNode)
建立子节点内容并加入到子节点之下