python写xml文件的操作实例
本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下:
要生成的xml文件格式如下:
<?xmlversion="1.0"?> <!--Simplexmldocument__chapter8--> <book> <title> samplexmlthing </title> <author> <name> <first> ma </first> <last> xiaoju </last> </name> <affiliation> SpringsWidgets,Inc. </affiliation> </author> <chapternumber="1"> <title> First </title> <para> Ithinkwidgetsaregreate.Youshouldbuylotsofthemforom <company> SpirngyWidgts,Inc </company> </para> </chapter> </book>
Python实现代码如下:
fromxml.domimportminidom,Node doc=minidom.Document() doc.appendChild(doc.createComment("Simplexmldocument__chapter8")) #generatethebook book=doc.createElement('book') doc.appendChild(book) #thetitle title=doc.createElement('title') title.appendChild(doc.createTextNode("samplexmlthing")) book.appendChild(title) #theauthorsection 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("SpringsWidgets,Inc.")) author.appendChild(affiliation) #Thechapter 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("Ithinkwidgetsaregreate.\ Youshouldbuylotsofthemforom")) company=doc.createElement('company') company.appendChild(doc.createTextNode("SpirngyWidgts,Inc")) para.appendChild(company) chapter.appendChild(para) printdoc.toprettyxml()
希望本文所述对大家的Python程序设计有所帮助。