我正在尝试从具有所示结构的XML数据文件中读取数组。 通过使用How do I parse XML in Python?,我收到了以下内容,而没有我的数组。
key
输出:
<event id="1" settings="183" digitizer="LoremID" timestamp="42">
<triggershift samples="0"></triggershift>
<trace channel="0">2 4 1 2 1 23 5 4 2 4 2
</trace>
</event>
有人对如何读取设置和阵列有想法吗?
谢谢。
答案 0 :(得分:0)
代码:
import xml.etree.ElementTree as ET
content = """<event id="1" settings="183" digitizer="LoremID" timestamp="42">
<triggershift samples="0"></triggershift>
<trace channel="0">2 4 1 2 1 23 5 4 2 4 2</trace>
</event>"""
root = ET.fromstring(content)
settings = {**root.attrib}
for el in root:
settings[el.tag] = {**el.attrib}
if el.text:
array = el.text.split(" ")
settings[el.tag]["value"] = array
输出:
{
"id": "1",
"settings": "183",
"digitizer": "LoremID",
"timestamp": "42",
"triggershift": {
"samples": "0"
},
"trace": {
"channel": "0",
"value": [
"2",
"4",
"1",
"2",
"1",
"23",
"5",
"4",
"2",
"4",
"2"
]
}
}
更新。
如果要将array
元素转换为int
,则可以使用map()
:
settings[el.tag]["value"] = list(map(int, array))