Dam*_*ian 14 python-3.x windows-10
当我使用 xmltodict 加载下面的 xml 文件时,出现错误: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1
这是我的文件:
<?xml version="1.0" encoding="utf-8"?>
<mydocument has="an attribute">
<and>
<many>elements</many>
<many>more elements</many>
</and>
<plus a="complex">
element as well
</plus>
</mydocument>
Run Code Online (Sandbox Code Playgroud)
来源:
import xmltodict
with open('fileTEST.xml') as fd:
xmltodict.parse(fd.read())
Run Code Online (Sandbox Code Playgroud)
我在 Windows 10 上,使用 Python 3.6 和 xmltodict 0.11.0
如果我使用 ElementTree 它可以工作
tree = ET.ElementTree(file='fileTEST.xml')
for elem in tree.iter():
print(elem.tag, elem.attrib)
mydocument {'has': 'an attribute'}
and {}
many {}
many {}
plus {'a': 'complex'}
Run Code Online (Sandbox Code Playgroud)
注意:我可能遇到了换行问题。
注2:我在两个不同的文件上使用了Beyond Compare。
它在 UTF-8 BOM 编码的文件上崩溃,并在 UTF-8 文件上工作。
UTF-8 BOM 是一个字节序列 (EF BB BF),它允许阅读器将文件识别为以 UTF-8 编码。
小智 11
我想你忘了定义编码类型。我建议您尝试将该 xml 文件初始化为字符串变量:
import xml.etree.ElementTree as ET
import xmltodict
import json
tree = ET.parse('your_data.xml')
xml_data = tree.getroot()
#here you can change the encoding type to be able to set it to the one you need
xmlstr = ET.tostring(xml_data, encoding='utf-8', method='xml')
data_dict = dict(xmltodict.parse(xmlstr))
Run Code Online (Sandbox Code Playgroud)
小智 6
我遇到了同样的问题,只需指定 open 函数的编码即可解决。
在这种情况下,它会是这样的:
import xmltodict
with open('fileTEST.xml', encoding='utf8') as fd:
xmltodict.parse(fd.read())
Run Code Online (Sandbox Code Playgroud)
data: dict = xmltodict.parse(ElementTree.tostring(ElementTree.parse(path).getroot()))
Run Code Online (Sandbox Code Playgroud)
.json和的助手.xml我编写了一个小辅助函数来加载.json给.xml定的文件path。我想这对这里的一些人来说可能会派上用场:
import json
import xml.etree.ElementTree
def load_json(path: str) -> dict:
if path.endswith(".json"):
print(f"> Loading JSON from '{path}'")
with open(path, mode="r") as open_file:
content = open_file.read()
return json.loads(content)
elif path.endswith(".xml"):
print(f"> Loading XML as JSON from '{path}'")
xml = ElementTree.tostring(ElementTree.parse(path).getroot())
return xmltodict.parse(xml, attr_prefix="@", cdata_key="#text", dict_constructor=dict)
print(f"> Loading failed for '{path}'")
return {}
Run Code Online (Sandbox Code Playgroud)
笔记
如果你想去掉json 输出中的@和#text标记,请使用参数attr_prefix=""和cdata_key=""
通常xmltodict.parse()返回一个OrderedDict,但您可以使用参数更改它dict_constructor=dict
用法
path = "my_data.xml"
data = load_json(path)
print(json.dumps(data, indent=2))
# OUTPUT
#
# > Loading XML as JSON from 'my_data.xml'
# {
# "mydocument": {
# "@has": "an attribute",
# "and": {
# "many": [
# "elements",
# "more elements"
# ]
# },
# "plus": {
# "@a": "complex",
# "#text": "element as well"
# }
# }
# }
Run Code Online (Sandbox Code Playgroud)