使用python自带的xml.dom创建和解析xml
推荐
在线提问>>
python中的xml.dom模块使用的就是传统的dom解析api和方法。所以也就不写什么了,主要就是练习敲敲代码,继续熟悉python。本文通过xml.dom.minidom创建一个xml文档,然后再解析出来,用以熟悉相关接口方法的使用。
创建一个xml文档:
'''
Createdon2012-1-10
Createaxmldocument
@author:xiaojay
'''
fromxml.domimportminidom
doc=minidom.Document()
doc.appendChild(doc.createComment("Thisisasimplexml."))
booklist=doc.createElement("booklist")
doc.appendChild(booklist)
defaddBook(newbook):
book=doc.createElement("book")
book.setAttribute("id",newbook["id"])
title=doc.createElement("title")
title.appendChild(doc.createTextNode(newbook["title"]))
book.appendChild(title)
author=doc.createElement("author")
name=doc.createElement("name")
firstname=doc.createElement("firstname")
firstname.appendChild(doc.createTextNode(newbook["firstname"]))
lastname=doc.createElement("lastname")
lastname.appendChild(doc.createTextNode(newbook["lastname"]))
name.appendChild(firstname)
name.appendChild(lastname)
author.appendChild(name)
book.appendChild(author)
pubdate=doc.createElement("pubdate")
pubdate.appendChild(doc.createTextNode(newbook["pubdate"]))
book.appendChild(pubdate)
booklist.appendChild(book)
addBook({"id":"1001","title":"Anapple","firstname":"Peter","lastname":"Zhang","pubdate":"2012-1-12"})
addBook({"id":"1002","title":"Love","firstname":"Mike","lastname":"Li","pubdate":"2012-1-10"})
addBook({"id":"1003","title":"Steve.Jobs","firstname":"Tom","lastname":"Wang","pubdate":"2012-1-19"})
addBook({"id":"1004","title":"HarryPotter","firstname":"Peter","lastname":"Chen","pubdate":"2012-11-11"})
f=file("book.xml","w")
doc.writexml(f)
f.close()
通过doc.toprettyxml(indent,newl,encoding)方法可以优雅显示xml文档,但是要避免直接写入文本,否则会给解析带来麻烦,尽量使用自带的writexml方法。
生成的文档内容:
Peter
Zhang
2012-1-12
.................
解析该xml文档:
'''
Createdon2012-1-10
Scanaxmldoc
@author:xiaojay
'''
fromxml.domimportminidom,Node
classbookscanner:
def__init__(self,doc):
forchildindoc.childNodes:
ifchild.nodeType==Node.ELEMENT_NODE\
andchild.tagName=="book":
bookid=child.getAttribute("id")
print"*"*20
print"Bookid:",bookid
self.handle_book(child)
defhandle_book(self,node):
forchildinnode.childNodes:
ifchild.nodeType==Node.ELEMENT_NODE:
ifchild.tagName=="title":
print"Title:",self.getText(child.firstChild)
ifchild.tagName=="author":
self.handle_author(child)
ifchild.tagName=="pubdate":
print"Pubdate:",self.getText(child.firstChild)
defgetText(self,node):
ifnode.nodeType==Node.TEXT_NODE:
returnnode.nodeValue
else:return""
defhandle_author(self,node):
author=node.firstChild
forchildinauthor.childNodes:
ifchild.nodeType==Node.ELEMENT_NODE:
ifchild.tagName=="firstname":
print"Firstname:",self.getText(child.firstChild)
ifchild.tagName=="lastname":
print"Lastname:",self.getText(child.firstChild)
doc=minidom.parse("book.xml")
forchildindoc.childNodes:
ifchild.nodeType==Node.COMMENT_NODE:
print"Conment:",child.nodeValue
ifchild.nodeType==Node.ELEMENT_NODE:
bookscanner(child)
以上内容为大家介绍了使用python自带的xml.dom创建和解析xml,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。