12

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'
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186

2 Answers2

14

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

from xml.parsers.expat import ExpatError
falsetru
  • 357,413
  • 63
  • 732
  • 636
8

Found it, within xmltodict module itself, so no need to import it separately from xml module

>>> try:                                             
...     xml_dict = xmltodict.parse(xml_data)
... except xmltodict.expat.ExpatError:
...     print "that's right"
... 
that's right
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186