模塊:xmllib
xmllib 是一個(gè)非驗(yàn)證的低級語法分析器。應(yīng)用程序員使用的 xmllib 可以覆蓋 XMLParser 類,并提供處理文檔元素(如特定或類屬標(biāo)記,或字符實(shí)體)的方法。從 Python 1.5x 到 Python 2.0+ 以來, xmllib 的使用方法并沒變化;在絕大多數(shù)情況下更好的選擇是使用 SAX 技術(shù),它也是種面向流的技術(shù),對語言和開發(fā)者來說更為標(biāo)準(zhǔn)。
本文中的示例與原來專欄中的相同:包括一個(gè)叫做 quotations.dtd 的 DTD 以及這個(gè) DTD 的文檔 sample.xml (請參閱 參考資料,以獲取本文中提到的文件的檔案)。以下的代碼顯示了 sample.xml 中每段引言的前幾行,并生成了非常簡單的未知標(biāo)記和實(shí)體的 ASCII 指示符。經(jīng)過分析的文本作為連續(xù)流來處理,所使用的任何累加器都由程序員負(fù)責(zé)(如標(biāo)記中的字符串 (#PCDATA),或所遇到的標(biāo)記的列表或詞典)。
清單 1: try_xmllib.py
import xmllib, string classQuotationParser (xmllib.XMLParser): """Crude xmllib extractor for quotations.dtd document""" def__init__ (self): xmllib.XMLParser.__init__(self) self.thisquote = '' # quotation accumulator defhandle_data (self, data): self.thisquote = self.thisquote + data defsyntax_error (self, message): pass defstart_quotations (self, attrs): # top level tag print '--- Begin Document ---' defstart_quotation (self, attrs): print 'QUOTATION:' defend_quotation (self): print string.join(string.split(self.thisquote[:230]))+'...', print '('+str(len(self.thisquote))+' bytes)/n' self.thisquote = '' defunknown_starttag (self, tag, attrs): self.thisquote = self.thisquote + '{' defunknown_endtag (self, tag): self.thisquote = self.thisquote + '}' defunknown_charref (self, ref): self.thisquote = self.thisquote + '?' defunknown_entityref (self, ref): self.thisquote = self.thisquote + '#' if __name__ == '__main__': parser = QuotationParser() for c in open("sample.xml").read(): parser.feed(c) parser.close()
驗(yàn)證
您可能需要展望標(biāo)準(zhǔn) XML 支持的未來的原因是,在進(jìn)行語法分析的同時(shí)需要進(jìn)行驗(yàn)證。不幸的是,標(biāo)準(zhǔn) Python 2.0 XML 包并不包括驗(yàn)證型語法分析器。
xmlproc 是 python 原有的語法分析器,它執(zhí)行幾乎完整的驗(yàn)證。如果需要驗(yàn)證型語法分析器, xmlproc 是 Python 當(dāng)前唯一的選擇。而且, xmlproc 提供其它語法分析器所不具備的各種高級和測試接口。
選擇一種語法分析器
如果決定使用 XML 的簡單 API (SAX) -- 它應(yīng)該用于復(fù)雜的事物,因?yàn)槠渌蟛糠止ぞ叨际窃谒幕A(chǔ)上建立的 -- 將為您完成許多語法分析器的分類工作。 xml.sax 模塊包含一個(gè)自動選擇“最佳”語法分析器的設(shè)施。在標(biāo)準(zhǔn) Python 2.0 安裝中,唯一能選擇的語法分析器是 expat ,它是種 C 語言編寫的快速擴(kuò)展。然而,也可以在 $PYTHONLIB/xml/parsers 下安裝另一個(gè)語法分析器,以備選擇。設(shè)置語法分析器很簡單:
新聞熱點(diǎn)
疑難解答
圖片精選