Python网络编程基础笔记-使用minidom生成XML文件
1.使用minidom创建XML文件
# -*- coding: cp936 -*-
"""
使用minidom生成XML
1.创建Element,createElement
2.添加子节点,appendChild
3.创建Text,createTextNode
4.创建属性,createAttribute
"""
from xml.dom import minidom,Node
# 创建Document
doc = minidom.Document()
# 创建book节点
book = doc.createElement("book")
doc.appendChild(book)
# 创建Title节点
title = doc.createElement("title")
text = doc.createTextNode("Sample XML Thing")
title.appendChild(text)
book.appendChild(title)
# 创建author节点
author = doc.createElement("author")
# 创建name节点
name = doc.createElement("name")
first = doc.createElement("first")
first.appendChild(doc.createTextNode("Benjamin"))
name.appendChild(first)
last = doc.createElement("last")
last.appendChild(doc.createTextNode("Smith"))
name.appendChild(last)
author.appendChild(name)
book.appendChild(author)
# author节点完毕
# 创建chapter节点
chapter = doc.createElement("chapter")
chapter.setAttribute("number","1")
title = doc.createElement("title")
title.appendChild(doc.createTextNode("Fisrt Chapter"))
chapter.appendChild(title)
para = doc.createElement("para")
para.appendChild(doc.createTextNode("I think widgets are great.you should buy lots \
of them from"))
company = doc.createElement("company")
company.appendChild(doc.createTextNode("Springy widgets,Inc"))
para.appendChild(company)
chapter.appendChild(para)
# chapter节点完毕
book.appendChild(chapter)
# book节点完毕
print doc.toprettyxml(indent = " ")
2.生成的XML文件
?xml version="1.0" ?>
book>
title>
Sample XML Thing
/title>
author>
name>
first>
Benjamin
/first>
last>
Smith
/last>
/name>
/author>
chapter number="1">
title>
Fisrt Chapter
/title>
para>
I think widgets are great.you should buy lots of them from
company>
Springy widgets,Inc
/company>
/para>
/chapter>
/book>