日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/6/17 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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##獲得文本值

?

轉載于:https://www.cnblogs.com/dengyg200891/p/5015999.html

總結

以上是生活随笔為你收集整理的python 之模块之 xml.dom.minidom解析xml的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。