开发者

ContentHandler is undefined

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜