xmltodict引发错误:找不到元素

2024-04-27 04:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想以编程方式将XML文件存储到数据库中,然后我将转换、分析和可视化数据。因为我比任何其他语言都精通python,所以我想把XML放到MongoDB中。因此,我尝试首先使用xmltodict将XML转换为JSON。 我正在使用colabs,但它不断抛出以下错误。你知道吗

!pip install -q xlrd
!git clone https://github.com/martinblech/xmltodict.git
!pip install xmltodict

import xmltodict
import json
import pprint

 from google.colab import files
 files.upload() #here I upload customer.xml

with open('customer.xml') as fd:
doc = xmltodict.parse(fd.read())

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(doc))

ExpatError                                Traceback (most recent call last)

<ipython-input-14-b14a90e48155> in <module>()
      1 with open('customer.xml') as fd:
----> 2     doc = xmltodict.parse(fd.read())
      3 
      4 pp = pprint.PrettyPrinter(indent=4)
      5 pp.pprint(json.dumps(doc))

/usr/local/lib/python3.6/dist-packages/xmltodict.py in parse(xml_input, encoding, expat, process_namespaces, namespace_separator, disable_entities, **kwargs)
    325         parser.ParseFile(xml_input)
    326     else:
--> 327         parser.Parse(xml_input, True)
    328     return handler.item
    329 

ExpatError: no element found: line 1, column 0

Tags: installpipimportgitjsoninputdocparse