python 之模塊之 xml.dom.minidom解析xml


# -*- coding: cp936 -*-
#python 27
#xiaodeng
#python 之模塊之 xml.dom.minidom解析xml
#http://www.cnblogs.com/coser/archive/2012/01/10/2318298.html
#python有三種方法解析XML,SAX,DOM,以及ElementTree




#import xml.dom
#這里主要通過xml.dom.minidom創建xml文檔,然后解析用以熟悉api
#常用方法function()
'''
minidom.parse(filename)                     #加載和讀取xml文件
doc.documentElement                         #獲取xml文檔對象
node.getAttribute(AttributeName)            #獲取xml節點屬性值
node.getElementsByTagName(TagName)          #獲取xml節點對象集合
node.childNodes                             #獲取子節點列表
node.childNodes[index].nodeValue        #獲取xml節點值
node.firstChild                             #訪問第一個節點
n.childNodes[0].data                        #獲得文本值
node.childNodes[index].nodeValue        #獲取XML節點值


doc=minidom.parse(filename)
doc.toxml('utf-8')                          #返回Node節點的xml表示的文本
'''



#test.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>
'''


#解析案例
from  xml.dom import  minidom
doc=minidom.parse('test.xml')                   #parse("foo.xml")
                                                #parseString("<foo><bar/></foo>")

#實例化
root=doc.documentElement                #注意沒括號


#文檔對象元素
print '--'*25
print root.nodeName             #節點名字,collection
print root.nodeValue            #節點的值,None
print root.nodeType             #節點類型,1
print root.ELEMENT_NODE         #1
print '--'*25


#在集合中獲取所有電影
nodes=root.getElementsByTagName('movie')        #獲取xml節點對象集合


#打印每部電影的詳細信息
for n in nodes:
    #print n#<DOM Element: movie at 0x1f9d968>

    
    #獲得電影的title的屬性值
    #print n.getAttribute('title')


    #獲取xml節點type對象的具體信息
    type= n.getElementsByTagName('type')[0]
    print "Type:%s" % type.childNodes[0].data##獲得文本值

 


免責聲明!

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



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