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)
答案 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