Catch ExpatError in xmltodict

I use xmltodict to parse xml.

If we ExpatError invalid xml, it throws an ExpatError .

How do I catch this? Here is what I tried in my ipython shell

 >>> import xmltodict >>> xml_data = """<?xml version="1.0" encoding="UTF-8" ?> ... <Website>""" >>> xml_dict = xmltodict.parse(xml_data) ExpatError: no element found >>> try: ... xml_dict = xmltodict.parse(xml_data) ... except ExpatError: ... print "that right" NameError: name 'ExpatError' is not defined >>> try: ... xml_dict = xmltodict.parse(xml_data) ... except xmltodict.ExpatError: ... print "that right" AttributeError: 'module' object has no attribute 'ExpatError' 
+7
python xml xmltodict
source share
2 answers

You need to import ExpatError from xml.parsers.expact .

 from xml.parsers.expat import ExpatError 
+8
source share

Found it in the xmltodict module xmltodict , so there is no need to import it separately from the xml module

 >>> try: ... xml_dict = xmltodict.parse(xml_data) ... except xmltodict.expat.ExpatError: ... print "that right" ... that right 
0
source share

All Articles