Python 3 : Unable to convert XML to dict using xmltodict

标签 python xml python-3.x character-encoding xmltodict

我正在尝试将数据从 XML 文件转换为 python 字典,但无法执行此操作。以下是我正在编写的代码。

import xmltodict
input_xml  = 'data.xml'  # This is the source file

with open(input_xml, encoding='utf-8', errors='ignore') as _file:
    data = _file.read()
    data = xmltodict.parse(data,'ASCII')
    print(data)
    exit()

执行此代码时,出现以下错误:
xml.parsers.expat.ExpatError:格式不正确(无效标记):第 239 行,第 40 列。
经过多次点击和尝试,我意识到我的xml在特定标签内有一些印地语字符,如下所示

<DECL>!! आप की सेवा में पुनः पधारे !!</DECL>

如何在运行 xmltodict.parse 之前忽略这些未编码的字符?

最佳答案

我猜这个问题与您正在读取的文件的编码有关。 你为什么要尝试用“ASCII”来解析它??

如果您尝试从不带 ASCII 的 Python 字符串读取相同的 XML,它应该可以正常工作:

import xmltodict
xml = """<DECL>!! आप की सेवा में पुनः पधारे !!</DECL>"""
xmltodict.parse(xml, process_namespaces=True)

结果:

OrderedDict([('DECL', '!! आप की सेवा में पुनः पधारे !!')]) 

使用具有单个输入行的文件,我可以正确解析它:

import xmltodict
input_xml  = 'tmp.txt'  # This is the source file

with open(input_xml, encoding='utf-8', mode='r') as _file:
    data = _file.read()
    data = xmltodict.parse(data)
    print(data)

问题很可能是您试图将其解析为“ASCII”。

关于Python 3 : Unable to convert XML to dict using xmltodict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56804129/

相关文章:

python-3.x - 为什么根据 python -a(b+c) != a(-b-c) ?

python - 解析嵌套的 json 并将其保存在 csv 中

xml - 如何指定 Nuget 架构?

python /JSON : Merge default and user configuration

java - 使用 Apache XMLBeans 对字符串中的 XML 实体进行编码

java - 选中时更改复选框颜色?

javascript - 访问网站时如何查找浏览器发出的所有 JavaScript 请求

python - 什么是 "python -m SimpleHTTPServer"的 Python 3 等价物

python - PyQt 入门

python - 将 2D 数组 reshape 为 3D 数组以进行 tiff 转换