我有这样的 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<Main xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns="http://cnig.gouv.fr/pcrs" gml:id="PlanCorpsRueSimplifie.1" version="2.0">
<gml:boundedBy>
</gml:boundedBy>
<featureMember>
<EmpriseEchangePCRS gml:id="EmpriseEchangePCRS.12189894">
<datePublication>2020-05-13</datePublication>
<type>Cellules</type>
<geometrie>
<gml:MultiSurface gml:id="EmpriseEchangePCRS.12189894-0" srsName="EPSG:3944" srsDimension="3">
<gml:surfaceMember>
<gml:Surface gml:id="EmpriseEchangePCRS.12189894-1">
<gml:patches>
</gml:patches>
</gml:Surface>
Run Code Online (Sandbox Code Playgroud)
我想将此文件转换为 json 文件。我尝试过这个,但我总是遇到同样的错误:
import xmltodict
import xml.etree.ElementTree as ET
root = ET.fromstring(open('JeuxTestv2.gml').read())
print(xmltodict.parse(root)['Main'])
Run Code Online (Sandbox Code Playgroud)
错误 :
Traceback (most recent call last):
File "C:\Users\xmltodict.py", line 6, in <module>
print(xmltodict.parse(root)['Main'])
File "C:\Users\xmltodict.py", line 327, in parse
parser.Parse(xml_input, True)
TypeError: a bytes-like object is required, not 'xml.etree.ElementTree.Element'
Run Code Online (Sandbox Code Playgroud)
我正在使用Python 3.7.6
当我尝试时,ET.fromstring() 将解析已经以字符串格式表示的 XML。
import os
import xml.etree.ElementTree as et
xml_doc_path = os.path.abspath(r"C:\dir1\path\to\file\example.xml")
root = et.fromstring(xml_doc_path)
print(root)
Run Code Online (Sandbox Code Playgroud)
该示例将显示以下错误
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 2
Run Code Online (Sandbox Code Playgroud)
我用的是ET。tostring()生成 XML 数据的字符串表示形式,它可以用作 xmltodict.parse() 的有效参数。单击此处获取 ET。tostring()文档。
下面的代码将解析 XML 文件并生成 JSON 文件。我使用了我自己的XML 示例。确保所有 XML 标签都正确关闭。
XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element1 attribute1 = 'first attribute'>
</element1>
<element2 attribute1 = 'second attribute'>
some data
</element2>
</root>
Run Code Online (Sandbox Code Playgroud)
Python代码:
import os
import xmltodict
import xml.etree.ElementTree as et
import json
xml_doc_path = os.path.abspath(r"C:\directory\path\to\file\example.xml")
xml_tree = et.parse(xml_doc_path)
root = xml_tree.getroot()
#set encoding to and method proper
to_string = et.tostring(root, encoding='UTF-8', method='xml')
xml_to_dict = xmltodict.parse(to_string)
with open("json_data.json", "w",) as json_file:
json.dump(xml_to_dict, json_file, indent = 2)
Run Code Online (Sandbox Code Playgroud)
输出: 上面的代码将创建以下 JSON 文件:
{
"root": {
"element1": {
"@attribute1": "first attribute"
},
"element2": {
"@attribute1": "second attribute",
"#text": "some data"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9617 次 |
| 最近记录: |