在python 3中进行expat解析

时间:2009-07-24 18:19:41

标签: python python-3.x python-2.6

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)

2 个答案:

答案 0 :(得分:14)

您需要将该文件打开为二进制文件:

parser.ParseFile(open('sample.xml', 'rb'))

答案 1 :(得分:3)

我在尝试使用Python 3的xmltodict模块时遇到了这个问题。在Python 2.7下我没有遇到任何问题,但在Python 3下我遇到了同样的错误。解决方案与@SilentGhost建议的解决方案相同:

import xmltodict

def convert(xml_file, xml_attribs=True):
    with open(xml_file, "rb") as f:    # notice the "rb" mode
        d = xmltodict.parse(f, xml_attribs=xml_attribs)
        return d