简体   繁体   English

通过xmltodict在python中解析xml文件

[英]parse xml file in python by xmltodict

I am using xmltodict library in python ( https://pypi.org/project/xmltodict/ ) to parse a xml file by: 我在python( https://pypi.org/project/xmltodict/ )中使用xmltodict库来解析xml文件:

import xmltodict
with open("MyXML.xml") as MyXML:
    doc = xmltodict.parse(MyXML.read())

The xml file looks good but I get this error: xml文件看起来不错但我收到此错误:

ExpatError: no element found: line 1, column 0

What should I do? 我该怎么办?

In my uses of xmltodict, I have always parsed a string and to get an xml string is use etree. 在使用xmltodict的过程中,我总是解析一个字符串,而使用etree来获取xml字符串。 Try this: 尝试这个:

import xml.etree.ElementTree as ET
import xmltodict

tree = ET.parse("MyXml.xml")
root = tree.getroot()
data = xmltodict.parse(ET.toString(root))

if you have your MyXml.xml file in a different locatin than this file you will need to handle that using file and the import os. 如果您的MyXml.xml文件位于与此文件不同的位置,则需要使用file和import os处理该文件

Good Luck, Hope this helps. 祝你好运,希望这会有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM