Catch ExpatError in xmltodict

Anshul Goyal picture Anshul Goyal · Aug 7, 2014 · Viewed 7.2k times · Source

I am using xmltodict to parse xml.

If we parse invalid xml, it throws up an ExpatError.

How do I catch this? Here is what I've 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's right"
NameError: name 'ExpatError' is not defined

>>> try:                      
...     xml_dict = xmltodict.parse(xml_data)
... except xmltodict.ExpatError:
...     print "that's right"
AttributeError: 'module' object has no attribute 'ExpatError'

Answer

falsetru picture falsetru · Aug 7, 2014

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

from xml.parsers.expat import ExpatError