Python基础(十一) 使用xml.dom 创建XML文件与解析

来源:互联网 发布:js的math方法 编辑:程序博客网 时间:2024/06/07 02:03

Python基础(十一) 使用xml.dom 创建XML文件与解析

创建XML文件

# -*- coding:UTF-8 -*-import xml.dom.minidom#创建XML文件doc = xml.dom.minidom.Document()doc.appendChild(doc.createComment("this is a simple xmll."))booklist = doc.createElement("booklist")doc.appendChild(booklist)def addBook(newBook):book = doc.createElement("book")book.setAttribute("name", newBook["name"])bookid = doc.createElement("bookid")bookid.appendChild(doc.createTextNode(newBook["id"]))book.appendChild(bookid)bookauthor = doc.createElement("author")bookauthor.appendChild(doc.createTextNode(newBook["author"]))book.appendChild(bookauthor)bookChapter = doc.createElement("chapter")chapter1 = doc.createElement("chapter1")chapter2 = doc.createElement("chapter2")chapter1.appendChild(doc.createTextNode(newBook["chapter1"]))chapter2.appendChild(doc.createTextNode(newBook["chapter2"]))bookChapter.appendChild(chapter1)bookChapter.appendChild(chapter2)book.appendChild(bookChapter)booklist.appendChild(book)addBook({"id":"0001","name":"果冻自传","author":"果冻","chapter1":"果冻自传第一章","chapter2":"果冻自传第二章"})addBook({"id":"0002","name":"GUODONG's LIFE","author":"GUODONG","chapter1":"GUODONG's LIFE chapter1","chapter2":"GUODONG's LIFE chapter2"})f = file("book.xml","w")doc.writexml(f)f.close()

运行可在当前目录生成 book.xml文件
<?xml version="1.0"?><!--this is a simple xmll.-->-<booklist>-<book name="果冻自传"><bookid>0001</bookid><author>果冻</author>-<chapter><chapter1>果冻自传第一章</chapter1><chapter2>果冻自传第二章</chapter2></chapter></book>-<book name="GUODONG's LIFE"><bookid>0002</bookid><author>GUODONG</author>-<chapter><chapter1>GUODONG's LIFE chapter1</chapter1><chapter2>GUODONG's LIFE chapter2</chapter2></chapter></book></booklist>


XML解析

from xml.dom import minidom , Nodefrom xml.dom.minidom import parseimport xml.dom.minidomDOMTree = xml.dom.minidom.parse("book.xml")collection = DOMTree.documentElementbooks = collection.getElementsByTagName("book")for book in books:print"*"*10if book.hasAttribute("name"):print "BookName: %s" % book.getAttribute("name")bookid = book.getElementsByTagName('bookid')[0]print "bookid :",bookid.childNodes[0].dataauthor = book.getElementsByTagName('author')[0]print "author :",author.childNodes[0].datachapters = book.getElementsByTagName('chapter')for chapter in chapters:chapter1 = chapter.getElementsByTagName('chapter1')[0]print "chapter1 :",chapter1.childNodes[0].datachapter2 = chapter.getElementsByTagName('chapter2')[0]print "chapter1 :",chapter2.childNodes[0].data

运行输出


0 0
原创粉丝点击