[代碼筆記] python 之xml解析_dom

#!python
#文件名: demo_xml_dom.py

#DOM解析
from xml.dom.minidom import parse
import xml.dom.minidom

#使用minidom解析器打開xml文檔
'''
    1.對於dom,他將xml文檔一次性解析(所以大文件初始化慢)
    2.每對標籤都是一個Element實例

'''

dom=xml.dom.minidom.parse('demo.xml')

root=dom.documentElement#dom代表整個文檔,dom.documentElement代表其根節點(即所有節點的集合)

if root.hasAttribute('shelf'):#判斷是否有這個屬性
    print('The RootElement has a attribute:shelf:',root.getAttribute('shelf'))

#在根標籤中獲取所有的電影

movies=root.getElementsByTagName('movie')#得到根節點下所有tag爲movie的Element集合

for movie in movies:#遍歷
    print('-------Movie------')
    if movie.hasAttribute('title'):#判斷
        print('Title: ',movie.getAttribute('title'))#獲取屬性

    type=movie.getElementsByTagName('type')[0]#獲取movie標籤下第一個tag爲type的Element
    print('Type: ',type.childNodes[0].data)

    format=movie.getElementsByTagName('format')[0]#同上
    print('Format: ', format.childNodes[0].data)


xml文件在上一篇文中有

發佈了62 篇原創文章 · 獲贊 23 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章