Python使用xml.dom解析xml


在菜鳥教程上找了個關於電影信息的xml類型的文檔,用python內置的xml.dom來解析提取一下信息。

先復習一下xml概念:

  • XML 指可擴展標記語言(EXtensible Markup Language)
  • XML 是一種標記語言,很類似 HTML
  • XML 的設計宗旨是傳輸數據,而非顯示數據
  • XML 被設計為具有自我描述性。
  • XML 是 W3C 的推薦標准

解析工具:

文件對象模型(Document Object Model,簡稱DOM),是W3C組織推薦的處理可擴展置標語言的標准編程接口。

解析原理:一個 DOM 的解析器在解析一個 XML 文檔時,一次性讀取整個文檔,把文檔中所有元素保存在內存中的一個樹結構里,之后可以利用DOM 提供的不同的函數來讀取或修改文檔的內容和結構,也可以把修改過的內容寫入xml文件。

 

XML代碼如下

目錄層次:

collect shelf

    movie title

          xxxx

          xxxx

Python解析代碼

from xml.dom.minidom import parse
import xml.dom.minidom

#使用Minidom解析器打開xml文檔
DOMTree = xml.dom.minidom.parse("mov.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
    print("Root element : %s " % collection.getAttribute("shelf"))

#self.getElementsByTagName("xx")取下級
#在集合里面獲取所有電影
movies = collection.getElementsByTagName("movie")

#打印每部電影的詳細信息
for movie in movies:
    print("********movies*********")
    if movie.hasAttribute("title"):
        print("title : %s" % movie.getAttribute("title"))

    type = movie.getElementsByTagName("type")[0]
    print("type : %s" % type.childNodes[0].data)

    format = movie.getElementsByTagName("format")[0]
    print("Format : %s" % format.childNodes[0].data)
    
    #有些電影里不一定有year這條信息,用if語句不會導致報錯
    if movie.getElementsByTagName("year"):
        year = movie.getElementsByTagName("year")[0]
        print("year : %s" % year.childNodes[0].data)

    if movie.getElementsByTagName("episodes"):
        episodes = movie.getElementsByTagName("episodes")[0]
        print("episodes : %s" % episodes.childNodes[0].data)

    rating = movie.getElementsByTagName("rating")[0]
    print("rating : %s" % rating.childNodes[0].data)

    stars = movie.getElementsByTagName("stars")[0]
    print("stars : %s" % stars.childNodes[0].data)

    description = movie.getElementsByTagName("description")[0]
    print("description : %s" % description.childNodes[0].data)

 

輸出結果:

Root element : New Arrivals 
********movies*********
title : Enemy Behind
type : War, Thriller
Format : DVD
year : 2003
rating : PG
stars : 10
description : Talk about a US-Japan war
********movies*********
title : Transformers
type : Anime, Science Fiction
Format : DVD
year : 1989
rating : R
stars : 8
description : A schientific fiction
********movies*********
title : Trigun
type : Anime, Action
Format : DVD
episodes : 4
rating : PG
stars : 10
description : Vash the Stampede!
********movies*********
title : Ishtar
type : Comedy
Format : VHS
rating : PG
stars : 2
description : Viewable boredom

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM