Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml.parsers.expat.ExpatError: not well-formed (invalid token)

When I use xmltodict to load the xml file below I get an error: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1

Here is my file:

<?xml version="1.0" encoding="utf-8"?>
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>

Source:

import xmltodict
with open('fileTEST.xml') as fd:
   xmltodict.parse(fd.read())

I am on Windows 10, using Python 3.6 and xmltodict 0.11.0

If I use ElementTree it works

tree = ET.ElementTree(file='fileTEST.xml')
    for elem in tree.iter():
            print(elem.tag, elem.attrib)

mydocument {'has': 'an attribute'}
and {}
many {}
many {}
plus {'a': 'complex'}

Note: I might have encountered a new line problem.
Note2: I used Beyond Compare on two different files.
It crashes on the file that is UTF-8 BOM encoded, and works om the UTF-8 file.
UTF-8 BOM is a sequence of bytes (EF BB BF) that allows the reader to identify a file as being encoded in UTF-8.

like image 845
Damian Avatar asked Feb 16 '18 07:02

Damian


1 Answers

I think you forgot to define the encoding type. I suggest that you try to initialize that xml file to a string variable:

import xml.etree.ElementTree as ET
import xmltodict
import json


tree = ET.parse('your_data.xml')
xml_data = tree.getroot()
#here you can change the encoding type to be able to set it to the one you need
xmlstr = ET.tostring(xml_data, encoding='utf-8', method='xml')

data_dict = dict(xmltodict.parse(xmlstr))
like image 62
Renz Paul Del Rosario Avatar answered Oct 23 '22 11:10

Renz Paul Del Rosario