parsing expatriés en python 3
-
19-09-2019 - |
Question
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'))
Les travaux ci-dessus en python 2.6 mais pas en python 3.0 - des idées pour le faire fonctionner en python 3 beaucoup apprécié. L'erreur que je reçois sur la ligne de ParseFile
est TypeError: read() did not return a bytes object (type=str)
La solution
vous devez ouvrir ce fichier sous forme binaire:
parser.ParseFile(open('sample.xml', 'rb'))
Autres conseils
Je suis tombé sur ce problème tout en essayant d'utiliser le module xmltodict avec Python 3. Sous Python 2.7 I eu aucun problème, mais en Python 3 j'ai eu cette même erreur. La solution est la même qui a été suggéré par @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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow