1 encoding:utf-8
2 '''
3 根据一个给定的XML Schema,使用DOM树的形式从空白文件生成一个XML。
4 '''
5 from xml.dom.minidom import Document
6
7 doc = Document() #创建DOM文档对象
8
9 bookstore = doc.createElement('bookstore') #创建根元素
10 bookstore.setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance")#设置命名空间
11 bookstore.setAttribute('xsi:noNamespaceSchemaLocation','bookstore.xsd')#引用本地XML Schema
12 doc.appendChild(bookstore)
13 ############book:Python处理XML之Minidom################
14 book = doc.createElement('book')
15 book.setAttribute('genre','XML')
16 bookstore.appendChild(book)
17
18 title = doc.createElement('title')
19 title_text = doc.createTextNode('Python处理XML之Minidom') #元素内容写入
20 title.appendChild(title_text)
21 book.appendChild(title)
22
23 author = doc.createElement('author')
24 book.appendChild(author)
25 author_first_name = doc.createElement('first-name')
26 author_last_name = doc.createElement('last-name')
27 author_first_name_text = doc.createTextNode('张')
28 author_last_name_text = doc.createTextNode('三')
29 author.appendChild(author_first_name)
30 author.appendChild(author_last_name)
31 author_first_name.appendChild(author_first_name_text)
32 author_last_name.appendChild(author_last_name_text)
33 book.appendChild(author)
34
35 price = doc.createElement('price')
36 price_text = doc.createTextNode('28')
37 price.appendChild(price_text)
38 book.appendChild(price)
39 ############book1:Python写网站之Django####################
40 book1 = doc.createElement('book')
41 book1.setAttribute('genre','Web')
42 bookstore.appendChild(book1)
43
44 title1 = doc.createElement('title')
45 title_text1 = doc.createTextNode('Python写网站之Django')
46 title1.appendChild(title_text1)
47 book1.appendChild(title1)
48
49 author1 = doc.createElement('author')
50 book.appendChild(author1)
51 author_first_name1 = doc.createElement('first-name')
52 author_last_name1 = doc.createElement('last-name')
53 author_first_name_text1 = doc.createTextNode('李')
54 author_last_name_text1 = doc.createTextNode('四')
55 author1.appendChild(author_first_name1)
56 author1.appendChild(author_last_name1)
57 author_first_name1.appendChild(author_first_name_text1)
58 author_last_name1.appendChild(author_last_name_text1)
59 book1.appendChild(author1)
60
61 price1 = doc.createElement('price')
62 price_text1 = doc.createTextNode('40')
63 price1.appendChild(price_text1)
64 book1.appendChild(price1)
65
66 ########### 将DOM对象doc写入文件
67 f = open('bookstore.xml','w')
68 f.write(doc.toprettyxml(indent = ''))
69 f.close()