Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch ExpatError in xmltodict

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'
like image 859
Anshul Goyal Avatar asked Aug 07 '14 13:08

Anshul Goyal


2 Answers

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

from xml.parsers.expat import ExpatError
like image 127
falsetru Avatar answered Nov 16 '22 22:11

falsetru


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
like image 7
Anshul Goyal Avatar answered Nov 16 '22 21:11

Anshul Goyal