python 3 中的 Expat 解析
import xml.parsers.expat
def start_element(name, attrs):
print('Start element:', name, attrs)
def end_element(name):
print('End element:', name)
def character_data(data):
print('Character data: %s' % data)
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.CharacterDataHandler = character_data
parser.ParseFile(open('sample.xml'))
上面的代码适用于 python 2.6,但不适用于 python 3.0 - 任何让它在 python 3 中工作的想法都非常感谢。 我在 ParseFile
行上收到的错误是 TypeError: read() did not return a bytes object (type=str)
import xml.parsers.expat
def start_element(name, attrs):
print('Start element:', name, attrs)
def end_element(name):
print('End element:', name)
def character_data(data):
print('Character data: %s' % data)
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.CharacterDataHandler = character_data
parser.ParseFile(open('sample.xml'))
The above works in python 2.6 but not in python 3.0 - any ideas to make it work in python 3 much appreciated. The error I get on the ParseFile
line is TypeError: read() did not return a bytes object (type=str)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将该文件作为二进制文件打开:
you need to open that file as binary:
我在尝试将 xmltodict 模块与 Python 3 一起使用时遇到了这个问题。在 Python 2.7 下我没有任何问题但在 Python 3 下我遇到了同样的错误。 解决方案与@SilentGhost 建议的相同:
I ran into this problem while trying to use the xmltodict module with Python 3. Under Python 2.7 I had no problems but under Python 3 I got this same error. The solution is the same that was suggested by @SilentGhost: