I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep gettin开发者_如何学编程g an error and I can't figure out why.
The first file is handlers.py
:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py
, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py
, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
You have to import ContentHandler in handlers.py as follows:
from xml.sax.handler import ContentHandler
This should do it.
精彩评论