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'
You need to import the ExpatError from xml.parsers.expact.
from xml.parsers.expat import ExpatError
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With