python3 createXml_xml.dom.py

"""
模塊:python3 createXml_xml.dom.py
功能:創建 xml 文檔。
參考:https://blog.csdn.net/kongsuhongbaby/article/details/84869838
知識點:
1.創建步驟:
    創建XML空白文檔
    創建根(元素)節點
    向根節點中加入子(元素)節點
    將 xml 內存對象寫到文件

2.doc.writexml(file, indent='', addindent='', newl='', encoding=None)
file:文件對象。
indent:根節點的縮進方式
allindent:子節點的縮進方式
newl:換行方式
encoding:保存文件的編碼方式
"""
import xml.dom.minidom

# 1.創建一個空 xml 文檔。
doc = xml.dom.minidom.Document()
# 2.創建根節點,添加到 doc,並給根節點添加屬性。
root = doc.createElement('companies')
doc.appendChild(root)
root.setAttribute('name', '公司信息')
# 3.創建子節點,添加到根節點。
company = doc.createElement('gloryRoad')
root.appendChild(company)
# 4.創建子節點,添加到父節點,並給元素節點添加文本節點
name = doc.createElement('name')
company.appendChild(name)
name.appendChild(doc.createTextNode('光榮之路'))
ceo = doc.createElement('CEO')
company.appendChild(ceo)
ceo.appendChild(doc.createTextNode('吳老師'))
# print(doc.toxml())
# 5.寫文件。
with open('company.xml', 'w', encoding="utf-8") as f:
    # 將內存中的 xml 寫入到文件
    doc.writexml(f, indent='', addindent='\t', newl='\n', encoding="utf-8")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章