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)
you need to open that file as binary:
parser.ParseFile(open('sample.xml', 'rb'))
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With