Python5-XML文件解析

發表于:2008-11-05來源:作者:點擊數: 標簽:文件解析
這次的學習目標是搞清楚基本的xml解析在Python的流程。 我準備解析下面這個文檔(關于xml的知識可以到http://www.w3.org上查看相關的Recommendations): 代碼: catalog; bookisbn="1-56592-724-9"; title;TheCathedraltheBazaar/title; author;EricS.Raymond/a
這次的學習目標是搞清楚基本的xml解析在Python的流程。

我準備解析下面這個文檔(關于xml的知識可以到http://www.w3.org上查看相關的Recommendations):
代碼:

<catalog>;

  <book isbn="1-56592-724-9">;
    <title>;The Cathedral & the Bazaar</title>;
    <author>;Eric S. Raymond</author>;
  </book>;
  <book isbn="1-56592-051-1">;
    <title>;Making TeX Work</title>;
    <author>;Norman Walsh</author>;
  </book>;
  <!-- imagine more entries here... -->;
</catalog>;



Python的標準模塊里包含了xml 處理的module。我們這次用的是xml.dom.minidom,一個迷你版的DOM API
代碼:

#! /usr/bin/python


import xml.dom.minidom
from xml.dom.minidom import Node

doc = xml.dom.minidom.parse("books.xml")

mapping = {}
for node in doc.getElementsByTagName("book"):
    isbn = node.getAttribute("isbn")
    L = node.getElementsByTagName("title")
    for node2 in L:
        title = ""
        for node3 in node2.childNodes:
            if node3.nodeType == Node.TEXT_NODE:
                title += node3.data
                mapping[isbn] = title
                # mapping now has the same value as in the SAX example:
                print(mapping)


通過這個程序,可以看到解析xml的文件的過程
minidom.parse返回的就是一個xml.dom.Document類型的實例。其實就是DOM中定義的Document了。通常的DOM的操作都是通過這個類來完成,比如例子中的建立ISBN和書名的對應關系表。對DOM的API,大家可以查看相關的文檔。

同時,這次引入了一個新的控制結構,就是for-loop。這個和C和Java的for循環有些區別(Java在5.0中也引入了這種循環)。這個循環是for-each-in格式的。而不是傳統的以初始值,步進值和中止條件控制循環過程的。

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97