11

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'
4

2 回答 2

14

您需要导入ExpatErrorfrom xml.parsers.expact

from xml.parsers.expat import ExpatError
于 2014-08-07T13:46:28.653 回答
6

在模块本身内找到它xmltodict,因此无需与xml模块分开导入

>>> try:                                             
...     xml_dict = xmltodict.parse(xml_data)
... except xmltodict.expat.ExpatError:
...     print "that's right"
... 
that's right
于 2014-08-07T13:49:50.463 回答