1.创建XML文件:
import codecs import xml.dom.minidom
doc=xml.dom.minidom.Document() print doc
root=doc.createElement("booklist")
print u"添加的xml标签为",root.tagName
root.setAttribute("type","science and engineering")
value=root.getAttribute("type")
print u"root元素的'type'属性值为:",value
#添加第一本书:
book=doc.createElement("book")
book.setAttribute("category","math")
title=doc.createElement("title")
title.appendChild(doc.createTextNode("learning math"))
author=doc.createElement("author")
author.appendChild(doc.createTextNode(u"张三"))
pageNumber=doc.createElement("pageNumber")
pageNumber.appendChild(doc.createTextNode("561"))
book.appendChild(title)
book.appendChild(author)
book.appendChild(pageNumber)
root.appendChild(book)
doc.appendChild(root)
#添加第二本书:
book=doc.createElement("book")
book.setAttribute("category","python")
title=doc.createElement("title")
title.appendChild(doc.createTextNode("learning python"))
author=doc.createElement("author")
author.appendChild(doc.createTextNode(u"李四"))
pageNumber=doc.createElement("pageNumber")
pageNumber.appendChild(doc.createTextNode("600"))
book.appendChild(title)
book.appendChild(author)
book.appendChild(pageNumber)
root.appendChild(book)
print doc.toxml()
#写入文件保存
fp=codecs.open(r"e:abcook.xml","w","utf-8")
doc.writexml(fp,indent="",addindent=" ",newl=" ",encoding="utf-8") fp.close()
2.解析XML文件:
from xml.dom.minidom import parse
DOMTree=parse(r"e:abcook.xml") #解析成内存中的一棵文档树
print type(DOMTree)
#print u"xml文档内容: %s"%DOMTree.toxml()
booklist=DOMTree.documentElement #获取文档树的根 print booklist
#判断存在某属性并获取属性值
if booklist.hasAttribute("type"):
print u"booklist元素存在type属性"
print u"booklist元素的type属性值是:%s"%booklist.getAttribute("type")
else:
print u"booklist元素不存在type属性"
#获取节点元素
books=booklist.getElementsByTagName("book")
print type(books)
print books
print u"book节点的个数:",len(books)
print "*"*20
for book in books:
if book.hasChildNodes():
#获取所有子节点对象
print book.childNodes
#获取节点文本值
title=book.getElementsByTagName("title")
print "title is:",title[0].childNodes[0].data
else:
print u"不存在叶子节点"