本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下:
要生成的xml文件格式如下:
sample xml thing
ma
xiaoju
springs widgets, inc.
first
i think widgets are greate.you should buy lots of them forom
spirngy widgts, inc
python实现代码如下:
from xml.dom import minidom, node
doc = minidom.document()
doc.appendchild(doc.createcomment(“simple xml document__chapter 8”))
#generate the book
book = doc.createelement(‘book’)
doc.appendchild(book)
#the title
title = doc.createelement(‘title’)
title.appendchild(doc.createtextnode(“sample xml thing”))
book.appendchild(title)
#the author section
author = doc.createelement(“author”)
book.appendchild(author)
name = doc.createelement(‘name’)
author.appendchild(name)
firstname = doc.createelement(‘first’)
firstname.appendchild(doc.createtextnode(“ma”))
name.appendchild(firstname)
lastname = doc.createelement(‘last’)
name.appendchild(lastname)
lastname.appendchild(doc.createtextnode(“xiaoju”))
affiliation = doc.createelement(“affiliation”)
affiliation.appendchild(doc.createtextnode(“springs widgets, inc.”))
author.appendchild(affiliation)
#the chapter
chapter = doc.createelement(‘chapter’)
chapter.setattribute(‘number’, ‘1’)
title = doc.createelement(‘title’)
title.appendchild(doc.createtextnode(“first”))
chapter.appendchild(title)
book.appendchild(chapter)
para = doc.createelement(‘para’)
para.appendchild(doc.createtextnode(“i think widgets are greate.\
you should buy lots of them forom”))
company = doc.createelement(‘company’)
company.appendchild(doc.createtextnode(“spirngy widgts, inc”))
para.appendchild(company)
chapter.appendchild(para)
print doc.toprettyxml()
希望本文所述对大家的python程序设计有所帮助。