可爱的 Python:将 XML 和 Python结合起来
2007-03-29 12:03:13 来源:WEB开发网核心提示: # try_xmllib.py #import xmllib, stringclass QuotationParser(xmllib.XMLParser):"""Crude xmllib extractor for quotations.dtd documen
#-------------------- try_xmllib.py --------------------#
import xmllib, string
class QuotationParser(xmllib.XMLParser):
"""Crude xmllib extractor for quotations.dtd document"""
def __init__(self):
xmllib.XMLParser.__init__(self)
self.thisquote = '' # quotation accumulator
def handle_data(self, data):
self.thisquote = self.thisquote + data
def syntax_error(self, message): pass
def start_quotations(self, attrs): # top level tag
print '--- Begin Document ---'
def start_quotation(self, attrs):
print 'QUOTATION:'
def end_quotation(self):
print string.join(string.split(self.thisquote[:230]))+'...',
print '('+str(len(self.thisquote))+' bytes)
'
self.thisquote = ''
def unknown_starttag(self, tag, attrs):
self.thisquote = self.thisquote + '{'
def unknown_endtag(self, tag):
self.thisquote = self.thisquote + '}'
def unknown_charref(self, ref):
self.thisquote = self.thisquote + '?'
def unknown_entityref(self, ref):
self.thisquote = self.thisquote + '#'
if __name__ == '__main__':
parser = QuotationParser()
for c in open("sample.xml").read():
parser.feed(c)
parser.close()
更多精彩
赞助商链接