# -*- coding: cp936-*- """ 使用minidom產生XML 1.建立Element,createElement 2.添加子節點,appendChild 3.建立Text,createTextNode 4.建立屬性,createAttribute
res = minidom.Document() query = res.createElement("queryItems") query.setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance') query.setAttribute('xsi:schemaLocation','http://www.taobao.com/schema/personalhomepage queryItems.xsd') query.setAttribute('xmlns','http://www.xxx.com/schema/personalhomepage') query.setAttribute('xmlns:header','http://www.xxx.com/schema/personalhomepage/extend/headerType')
""" 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= " ")
|