0

I am trying to read an array from an XML data file with the shown structure. By using How do I parse XML in Python? I received the following without my array.

<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>

Output:

{'id': '1', 
'settings': '183', 
'digitizer': 'LoremID', 
'timestamp': '42', 
'triggershift': {'samples': '0'}, 
'trace': {'channel': '0'}}

Does anyone have ideas on how to read both the settings and the array?

Thanks in advance.

jlee88my
  • 2,935
  • 21
  • 28
Zwar2841
  • 3
  • 1

1 Answers1

0

Code:

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

Output:

{
    "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"
        ]
    }
}

Upd.

If you want to convert array elements to int, you can use map():

settings[el.tag]["value"] = list(map(int, array))
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35