python写xml文件的操作实例
程序员文章站
2023-12-12 08:36:52
本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下:
要生成的xml文件格式如下:
本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下:
要生成的xml文件格式如下:
<?xml version="1.0" ?> <!--simple xml document__chapter 8--> <book> <title> sample xml thing </title> <author> <name> <first> ma </first> <last> xiaoju </last> </name> <affiliation> springs widgets, inc. </affiliation> </author> <chapter number="1"> <title> first </title> <para> i think widgets are greate.you should buy lots of them forom <company> spirngy widgts, inc </company> </para> </chapter> </book>
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程序设计有所帮助。