# -*-Coding: cp936 -*- """ Use minidom to generate xml 1. Create element and createelement 2. Add a subnode and appendchild 3. Create text and createtextnode 4. Create an attribute, 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
# Create document Doc = minidom. Document () # Create a book Node Book = Doc. createelement ("book ") Doc. appendchild (book) # Create a title Node Title = Doc. createelement ("title ") TEXT = Doc. createtextnode ("sample XML thing ") Title. appendchild (text) Book. appendchild (title) # Creating an author Node Author = Doc. createelement ("author ") # Create a Name Node 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 node completed
# Create a chapter Node 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 ter node completion Book. appendchild (chapter) # Book node completion
print doc.toprettyxml(indent= " ")
|