在xmltodict中捕获ExpatError

时间:2014-08-07 13:42:05

标签: python xml python-2.7 xmltodict

我使用xmltodict来解析xml。

如果我们解析无效的xml,它会抛出ExpatError

我怎么抓住这个?这是我在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'

2 个答案:

答案 0 :(得分:10)

您需要从ExpatError导入xml.parsers.expact

from xml.parsers.expat import ExpatError

答案 1 :(得分:1)

xmltodict模块本身内找到它,因此无需从xml模块中单独导入

>>> try:                                             
...     xml_dict = xmltodict.parse(xml_data)
... except xmltodict.expat.ExpatError:
...     print "that's right"
... 
that's right