一、DOM(Document Object Model)
將XML數據在內存中解析成一個樹,通過對樹的操作來操作XML。
二、
XML實例文件movies.xml:
<collection shelf="New Arrivals"> <movie title="Enemy Behind"> <!-- 屬性(attribute) --> <type>War, Thriller</type> <!-- 元素(element) --> <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> </collection>
解析代碼:
from xml.dom.minidom import parse import xml.dom.minidom # 使用minidom解析器打開 XML 文檔 DOMTree = xml.dom.minidom.parse("e:/movies.xml") collection = DOMTree.documentElement if collection.hasAttribute("shelf"): print ("Root element : %s" % collection.getAttribute("shelf")) # 在集合中獲取所有電影 movies = collection.getElementsByTagName("movie") # 打印每部電影的詳細信息 for movie in movies: print ("*****Movie*****") if movie.hasAttribute("title"): print ("Title: %s" % movie.getAttribute("title")) type = movie.getElementsByTagName('type')[0] # [0]:若存在同名的,用以區分 print ("Type: %s" % type.childNodes[0].data) # type.childNodes[0]表示type標簽下的第一個內容或者子標簽 format = movie.getElementsByTagName('format')[0] print ("Format: %s" % format.childNodes[0].data) rating = movie.getElementsByTagName('rating')[0] print ("Rating: %s" % rating.childNodes[0].data) description = movie.getElementsByTagName('description')[0] print ("Description: %s" % description.childNodes[0].data)
childNodes -----> 嵌套列表???
三、常用方法:
minidom.parse(filename) #加載讀取XML文件 doc.documentElement #獲取XML文檔對象 node.getAttribute(AttributeName) #獲取XML節點屬性值 node.getElementsByTagName(TagName) #獲取XML節點對象集合 node.childNodes #返回子節點列表。 node.childNodes[index].nodeValue #獲取XML節點值 node.firstChild #訪問第一個節點。等價於pagexml.childNodes[0] doc = minidom.parse(filename) doc.toxml('UTF-8') #返回Node節點的xml表示的文本 Node.attributes["id"] #訪問元素屬性 a.name #就是上面的 "id" a.value #屬性的值
http://www.cnblogs.com/kaituorensheng/p/4493306.html