Domanda

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'))

I lavori di cui sopra in Python 2.6, ma non in Python 3.0 - tutte le idee per farlo funzionare in Python 3 molto apprezzato. L'errore che ottengo sulla linea ParseFile è TypeError: read() did not return a bytes object (type=str)

È stato utile?

Soluzione

è necessario aprire il file in formato binario:

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

Altri suggerimenti

Mi sono imbattuto in questo problema durante il tentativo di utilizzare la xmltodict modulo con Python 3. In Python 2.7 I non ha avuto problemi, ma sotto Python 3 ho ottenuto questo stesso errore. La soluzione è la stessa che è stata suggerita da @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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top