Take the 2-minute tour ×

I want to parse a file with minidom:

with codecs.open(fname, encoding="utf-8") as xml:
   dom = parse(xml)

Returns a UnicodeEncodeError. The XML file is in UTF-8 without BOM format and has


in the first line.

If I first read the file, .encode("utf-8") it and pass it to parseString, it works. Is there a way to parse an UTF-8 XML file directly with minidom.parse?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Leave the decoding to the XML parser; it'll detect what codec to use. Open the file without converting to unicode:

with open(fname) as xml:
    dom = parse(xml)

Note the use of the standard function open() instead of codecs.open().

This applies to any XML parser; it is the job of the parser to determine from the XML prologue what codec to use for parsing the document. If no prologue is present then UTF-8 is the default.

share|improve this answer
To elaborate a bit in the answer, the OP problem is that minidom.parse expects a string of raw bytes and it will apply the declared encoding as needed, but they are are passing a string of chars... then it tries to decode the already-decoded chars and fails. –  rodrigo Jul 16 '13 at 13:19

Your Answer


