#!/usr/bin/python
import xml.sax
import pprint
from xml.sax import make_parser, parseString
class BookHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.inTitle = 0
self.mapping = {}
def startElement(self, name, attributes):
if name == "book":
self.buffer = ""
self.isbn = attributes["isbn"]
elif name == "title":
self.inTitle = 1
def characters(self, data):
if self.inTitle:
self.buffer += data
def endElement(self, name):
if name == "title":
self.inTitle = 0
self.mapping[self.isbn] = self.buffer
parser = xml.sax.make_parser()
handler = BookHandler()
parser.setContentHandler(handler)
document = file("bbb.xml")
text = document.read().replace("GB2312",'utf-8',1)
utfdoc = text.decode("gb2312").encode("utf-8")
xml.sax.parseString(text,handler)
pprint.pprint(handler.mapping)
注:python 的xml.sax对中文的支持不好,所以这里先把xml里的gb2312先替换成utf-8,并把文件的编码也改成utf-8,然后再处理。注意处理完后再把他还原成gb2312,要不可能会显示异常。
另外,有些情况直接用parser.parse(document)也可以,parser.parse()后面带的参数为文件名,或文件句柄,parser.parse后可带handler参数,该参数必须是SAX ContentHandler 实例。
parseString( | string, handler[, error_handler]) |
类似于parse(),带的参数为字符串,需要通过xml.sax.parseString()来调用。