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'
您需要导入ExpatError
从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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.