標籤:
python建立xml執行個體
模仿下面的xml檔案,使用python指令碼進行建立。
<?xml version=‘1.0‘?><database> <user username="user" fromAddress="[email protected]" fullName="John Q. User" password="pass"> <subscription host="mail.hotmail.com" autoConnect="false" password="bar" type="pop3" username="user1234"> </subscription> <subscription host="mail.yahoo.com" autoConnect="false" password="foo" type="imap" username="jquser"> </subscription> </user></database>
使用代碼如下:
#coding=utf-8from xml.dom import minidomdoc = minidom.Document()#建立database根節點db = doc.createElement("database")#將根節點添加入dom對象doc.appendChild(db)#建立database的子節點useruser = doc.createElement("user")user.setAttribute(‘fromAddress‘,‘[email protected]‘)user.setAttribute(‘fullName‘,‘John Q. User‘)user.setAttribute(‘password‘,‘pass‘)db.appendChild(user)#建立user的子節點subscriptionsubs = doc.createElement(‘subscription‘)subs.setAttribute(‘host‘,‘mail.hotmail.com‘)subs.setAttribute(‘autoConnect‘,‘false‘)subs.setAttribute(‘password‘,‘bar‘)subs.setAttribute(‘type‘,‘pop3‘)subs.setAttribute(‘username‘,‘user1234‘)user.appendChild(subs)#建立user的子節點subscriptionsubs2 = doc.createElement(‘subscription‘)subs2.setAttribute(‘host‘,‘mail.yahoo.com‘)subs2.setAttribute(‘autoConnect‘,‘false‘)subs2.setAttribute(‘password‘,‘foo‘)subs2.setAttribute(‘type‘,‘pop3‘)subs2.setAttribute(‘username‘,‘jquser‘)user.appendChild(subs2)#組建檔案f = file("book.xml","w")‘‘‘doc.writexml(f, "/t", "/t", "/n", "utf-8") #第一個參數f就是你的目標檔案對象,第二個參數好像是<?xml>和下面一個根節點的縮排排列格式, 第三個參數好像是其他節點與子節點的縮排排列格式,第四個參數制定了換行的格式(如果你填入" ",那就不換行了,所有的xml都縮在了一行上面 :) ) ,第五個參數制定了xml內容的編碼。除了第一個參數是必須的,其他參數都是可選擇的。援引使用PYTHON建立XML文檔,未作考證‘‘‘doc.writexml(f,‘‘,‘\t‘,‘\n‘,‘utf-8‘)f.close()
檔案最終輸出如下:
<?xml version="1.0" encoding="utf-8"?><database> <user fromAddress="[email protected]" fullName="John Q. User" password="pass"> <subscription autoConnect="false" host="mail.hotmail.com" password="bar" type="pop3" username="user1234"/> <subscription autoConnect="false" host="mail.yahoo.com" password="foo" type="pop3" username="jquser"/> </user></database>
本文參考:使用python內建的xml.com建立和解析xml
python使用 minidom建立xml執行個體