python3 readWriteAbc_xml.dom.py

abc.xml 文檔:
 

<?xml version="1.0" encoding="utf-8"?>
<catalog>
    <maxid>4</maxid>
    <login username="python" password='123456'>
        <caption>Python</caption>
        <item id="4">
            <caption>測試</caption>
        </item>
    </login>
    <item id="i2">
        <caption>Zope</caption>
    </item>
</catalog>

python3 代碼:

"""
模塊:python3 readWriteAbc_xml.dom.py
功能:python 讀寫 XML 文件。
參考:
https://blog.csdn.net/kongsuhongbaby/article/details/84869838
https://blog.csdn.net/kongsuhongbaby/article/details/84869838
知識點:
xml.dom.minidom 知識點.txt
"""
import xml.dom.minidom

# 1.解析 xml 文檔。
doc = xml.dom.minidom.parse('abc.xml')
# 2.root, 根節點。
root = doc.documentElement
# 3.doc/parentNode.getElementsByTagName() -> [ node1,node2,...]
# node.getAttribute(attname) -> 節點屬性。
print("\n3.")
login = doc.getElementsByTagName('login')[0]
username = login.getAttribute("username")
print("username:", username)
# username: python
items = root.getElementsByTagName('item')
print("id:", items[0].getAttribute("id"))
# id: 4

# 4.文本節點。
print("\n4.")
captions = doc.getElementsByTagName('caption')
# print(captions[0].firstChild)
# <DOM Text node "'Python'">
print(captions[0].firstChild.data)  # Python
print(captions[1].firstChild.data)  # 測試
print(captions[2].firstChild.data)  # Zope

# 5.創建新元素節點,並設置屬性,添加到根元素。
hotspot = doc.createElement("hotspot")
root.appendChild(hotspot)
#  name="spot4" style="skin_hotspotstyle" ath="10" atv="6" linkedscene="scene_ladybug_panoramic_000001"
hotspot.setAttribute("name", "spot4")
hotspot.setAttribute("style", "skin_hotspotstyle")
hotspot.setAttribute("ath", "10")
hotspot.setAttribute("atv", "6")
hotspot.setAttribute("linkedscene", "scene_ladybug_panoramic_000001")
# print(root.toxml())
# 6.寫文件。
with open('abc2.xml', 'w', encoding="utf-8") as f:
    # 將內存中的 xml 寫入到文件
    doc.writexml(f, indent='', addindent='', newl='', encoding="utf-8")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章