xml解析

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>



#######################################################################################

__author__ = 'sea'
#coding: utf-8
from xml.dom.minidom import parse
import xml.dom.minidom

#加載讀取xml文件
DOMTree=xml.dom.minidom.parse("XTest.xml")
#讀取xml對象
collection=DOMTree.documentElement

'''
if collection.hasAttribute("shelf"):
    print("Root element: %s " % collection.getAttribute("shelf"))
'''

#獲取xml節點集合
movies=collection.getElementsByTagName("movie")

for movie in movies:
    #獲取xml節點屬性值
    if movie.hasAttribute("title"):
        print("Title: %s " % movie.getAttribute("title"))

    type=movie.getElementsByTagName('type')[0]
    #返回子節點列表
    print(type.childNodes[0].nodeValue)
    #print("Type : %s" % type.childNodes[0].data)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章