gpt4 book ai didi

python - 将 XML 转换为 Dict/JSON

转载 作者:行者123 更新时间:2023-12-01 09:16:13 27 4
gpt4 key购买 nike

我需要将 XML 文件转换为 JSON。

XML 脚本示例如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="Overpass API 0.7.55.3 9da5e7ae">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2018-06-17T15:31:02Z"/>
<node id="330268305" lat="52.5475000" lon="13.3850775">
<tag k="direction" v="240-60"/>
<tag k="tourism" v="viewpoint"/>
<tag k="wheelchair" v="no"/>
</node>
<node id="330269757" lat="52.5473115" lon="13.3843131">
<tag k="direction" v="240-60"/>
<tag k="tourism" v="viewpoint"/>
<tag k="wheelchair" v="limited"/>
</node>
<way id="281307598">
<center lat="52.4934004" lon="13.4843019"/>
<nd ref="2852755795"/>
<nd ref="3772363803"/>
<nd ref="3772363802"/>
<nd ref="2852755796"/>
<nd ref="2852755797"/>
<nd ref="2852755798"/>
<nd ref="2852755795"/>
<tag k="man_made" v="tower"/>
<tag k="tourism" v="viewpoint"/>
<tag k="tower:type" v="observation"/>
<tag k="wheelchair" v="yes"/>
</way>
</osm>

到目前为止执行的代码

import xml.etree.ElementTree as ET
import json

input_file = r"D:\berlin\trial_xml\berlin_viewpoint_locations.xml"

tree = ET.parse(input_file)
root = tree.getroot()

result_list = [{k: (item.get(k) if k != 'extra' else
{i.get('k'): i.get('v') for i in item.iter('tag')})
for k in ('id', 'lat', 'lon', 'extra')}
for item in tree.findall("./node") + tree.findall('./way')]

print(result_list)

在一些 Stackoverflow 专家的帮助下,我已经取得了一半的成果。但是,我仍然需要了解如何:

  1. 附加隐藏在 <center lat="52.4934004" lon="13.4843019"/> 中的坐标同样result_list for nodes.
    It works for
    正如前面提到的“id”here .
  2. 附加所有引用文献 <nd ref="2852755795"/> <nd ref="3772363803"/> ,与 extra 的操作方式相同,例如嵌套列表。

最佳答案

当前代码不适合您的原因是数据结构不一样。我建议为每种 nodeway 类型提供独立的解析器。您已经在解析 node 类型,因此要解析 way ,可以构造一个相当简单的循环,如下所示:

way_list = []
for item in tree.findall("./way"):
# get the center node
center = item.find('center')

# get the refs for the nd nodes
nds = [nd.get('ref') for nd in item.iter('nd')]

# construct a dict and append to result list
way_list.append(dict(
id=item.get('id'),
lat=center.get('lat'),
lon=center.get('lon'),
nds=nds,
extra={i.get('k'): i.get('v') for i in item.iter('tag')},
))
print(way_list)

结果:

[{
'id': '281307598',
'lat': '52.4934004',
'lon': '13.4843019',
'nds': ['2852755795', '3772363803', '3772363802', '2852755796',
'2852755797', '2852755798', '2852755795'],
'extra': {
'man_made': 'tower',
'tourism': 'viewpoint',
'tower:type': 'observation',
'wheelchair': 'yes'
}
}]

关于python - 将 XML 转换为 Dict/JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51235041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com