【问题标题】:Catch ExpatError in xmltodict在 xmltodict 中捕获 ExpatError
【发布时间】:2014-08-07 13:42:05
【问题描述】:

我正在使用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'

【问题讨论】:

    标签: python xml python-2.7 xmltodict


    【解决方案1】:

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

    from xml.parsers.expat import ExpatError
    

    【讨论】:

    • 意识到我们也可以直接从 xmltodict 导入。感谢 +1 为我指明了正确的方向
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2012-05-22
      相关资源
      最近更新 更多