python 之模块之 xml.dom.minidom解析xml
生活随笔
收集整理的這篇文章主要介紹了
python 之模块之 xml.dom.minidom解析xml
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
# -*- 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創(chuàng)建xml文檔,然后解析用以熟悉api
#常用方法function()
'''
minidom.parse(filename) #加載和讀取xml文件
doc.documentElement #獲取xml文檔對象
node.getAttribute(AttributeName) #獲取xml節(jié)點屬性值
node.getElementsByTagName(TagName) #獲取xml節(jié)點對象集合
node.childNodes #獲取子節(jié)點列表
node.childNodes[index].nodeValue #獲取xml節(jié)點值
node.firstChild #訪問第一個節(jié)點
n.childNodes[0].data #獲得文本值
node.childNodes[index].nodeValue #獲取XML節(jié)點值doc=minidom.parse(filename)
doc.toxml('utf-8') #返回Node節(jié)點的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 #節(jié)點名字,collection
print root.nodeValue #節(jié)點的值,None
print root.nodeType #節(jié)點類型,1
print root.ELEMENT_NODE #1
print '--'*25#在集合中獲取所有電影
nodes=root.getElementsByTagName('movie') #獲取xml節(jié)點對象集合#打印每部電影的詳細信息
for n in nodes:#print n#<DOM Element: movie at 0x1f9d968>#獲得電影的title的屬性值#print n.getAttribute('title')#獲取xml節(jié)點type對象的具體信息type= n.getElementsByTagName('type')[0]print "Type:%s" % type.childNodes[0].data##獲得文本值
?
轉載于:https://www.cnblogs.com/dengyg200891/p/5015999.html
總結
以上是生活随笔為你收集整理的python 之模块之 xml.dom.minidom解析xml的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端小问题1——(最近好久没有发博客。。
- 下一篇: jQuery学习随笔(一)