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

时间:2022-08-24 22:39:12

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 , Node
from xml.dom.minidom import parse
import xml.dom.minidom

DOMTree = xml.dom.minidom.parse("book.xml")
collection = DOMTree.documentElement
books = collection.getElementsByTagName("book")
for book in books:
print"*"*10
if book.hasAttribute("name"):
print "BookName: %s" % book.getAttribute("name")

bookid = book.getElementsByTagName('bookid')[0]
print "bookid :",bookid.childNodes[0].data


author = book.getElementsByTagName('author')[0]
print "author :",author.childNodes[0].data

chapters = book.getElementsByTagName('chapter')
for chapter in chapters:

chapter1 = chapter.getElementsByTagName('chapter1')[0]
print "chapter1 :",chapter1.childNodes[0].data

chapter2 = chapter.getElementsByTagName('chapter2')[0]
print "chapter1 :",chapter2.childNodes[0].data

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