http://docs.python.org/library/xml.sax.html
请注意,您可以将“stream”对象传递给xml.sax.parse.这意味着您可以将任何具有类文件方法(如read)的对象传递给解析调用…创建自己的对象,首先将您的虚拟根开始标记,然后是文件内容,然后是虚拟根目录结束标签.我想你只需要实现read方法……但这可能取决于你将使用的sax解析器.
适用于我的示例:
import xml.sax
import xml.sax.handler
class PseudoStream(object):
def read_iterator(self):
yield ''
yield ''
for line in open('test.xml'):
yield line
yield ''
yield ''
def __init__(self):
self.ri = self.read_iterator()
def read(self, *foo):
try:
return self.ri.next()
except StopIteration:
return ''
class SAXHandler(xml.sax.handler.ContentHandler):
def startElement(self, name, attrs):
print name, attrs
d = xml.sax.parse(PseudoStream(), SAXHandler())