0

I have a XML file encoded in UTF-8 with some bad content that brokes my script when I try to parse it with:

from xml.etree import ElementTree as etree  
etree.parse(file).getroot()

I've seen some old answers where they use "recover=True" in the parser but after reading etree's docs it seems it's not allowed anymore. Also I can't manually replace the characters because I'm afraid this could happen again in the future with other characters, so I'm looking for a solution that completely removes any single non-allowed character. Is there any built-in function or way of doing this?

2

2 Answers 2

1

As suggested in the comments I just replaced the library for lxml and used the "recover" option for the parser. It's working fine now.

1
  • 1
    hello can you please furnish more detail to your code? I know it's an old topic but that would be appreciated
    – Solal
    Dec 7, 2020 at 16:58
1

in a similar use case i have this issue

exception = SAXParseException('reference to invalid character number')

that because my xml has this characters



this is my code to solve the problem

from lxml import etree
my_parser = etree.XMLParser(recover=True)
xml = etree.fromstring(dirty_xml_string, parser=my_parser)
cleaned_xml_string = etree.tostring(xml)

it works in my use-case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.