首页 > 代码库 > xml解析

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)


xml解析