導航:首頁 > 編程語言 > python怎麼建xml

python怎麼建xml

發布時間:2025-03-04 03:58:07

Ⅰ 如何用Python創建生成xml文檔文件的方法

1、內存數據產生

2、產生xml內存對象(也就是DOM樹)

3、產生根對象

4、往根對象里加數據

5、把xml內存對象寫到文件

下面是一個創建xml文檔的簡單實例:

importxml.dom.minidom#在內存中創建一個空的文檔doc=xml.dom.minidom.Document()
#創建一個根節點Managers對象root=doc.createElement('Managers')
#設置根節點的屬性root.setAttribute('company','xx科技')
root.setAttribute('address','科技軟體園')
#將根節點添加到文檔對象中doc.appendChild(root)

managerList=[{'name':'joy','age':27,'sex':'女'},
{'name':'tom','age':30,'sex':'男'},
{'name':'ruby','age':29,'sex':'女'}
]foriinmanagerList:
nodeManager=doc.createElement('Manager')
nodeName=doc.createElement('name')
#給葉子節點name設置一個文本節點,用於顯示文本內容
nodeName.appendChild(doc.createTextNode(str(i['name'])))

nodeAge=doc.createElement("age")
nodeAge.appendChild(doc.createTextNode(str(i["age"])))

nodeSex=doc.createElement("sex")
nodeSex.appendChild(doc.createTextNode(str(i["sex"])))

#將各葉子節點添加到父節點Manager中,
#最後將Manager添加到根節點Managers中
nodeManager.appendChild(nodeName)
nodeManager.appendChild(nodeAge)
nodeManager.appendChild(nodeSex)
root.appendChild(nodeManager)#開始寫xml文檔fp=open('c:\wcx\Manager.xml','w')
doc.writexml(fp,indent=' ',addindent=' ',newl=' ',encoding="utf-8")

執行結果:

<?xmlversion="1.0"encoding="utf-8"?>
<Managersaddress="科技軟體園"company="xx科技">
<Manager>
<name>joy</name>
<age>27</age>
<sex>女</sex>
</Manager>
<Manager>
<name>tom</name>
<age>30</age>
<sex>男</sex>
</Manager>
<Manager>
<name>ruby</name>
<age>29</age>
<sex>女</sex>
</Manager>
</Managers>

6.用Python自帶的寫xml文檔的API去寫,比較方便,後期容易維護。如果直接用打開文件的方式,一行一行的去寫,比較費時,也難以維護。

閱讀全文

與python怎麼建xml相關的資料

熱點內容
資料庫查詢系統源碼 瀏覽:614
php5314 瀏覽:354
完美國際安裝到哪個文件夾 瀏覽:666
什麼app可以掃一掃做題 瀏覽:537
程序員編碼論壇 瀏覽:923
淘點是什麼app 瀏覽:658
中國高等植物pdf 瀏覽:453
51單片機時間 瀏覽:181
後台如何獲取伺服器ip 瀏覽:265
單片機流水燈程序c語言 瀏覽:232
程序員第二職業掙錢 瀏覽:237
運行里怎麼輸入伺服器路徑 瀏覽:840
pythonstepwise 瀏覽:509
劉一男詞彙速記指南pdf 瀏覽:62
php認證級別 瀏覽:366
方舟編譯啥時候推送 瀏覽:1009
php手機驗證碼生成 瀏覽:675
哲學思維pdf 瀏覽:14
凌達壓縮機有限公司招聘 瀏覽:534
weblogic命令部署 瀏覽:36