XML file creation with Python: How to display the attributes of an element in multiple lines

145 views Asked by At

I am working with python on the creation of two types of files: EVFM and SMURF, which both follow the xml structure. One example of such files is the following:

EVFM

My approach is to use the xmltodict package with the unparse method, which transforms a dictionary into an xml-structured file.

My code is here:

mydict = OrderedDict({
        "eventfile": {
            "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
            "@xsi:schemaLocation": "http://esa.esoc.eventsgen_event_sample.xsd xmlns:http://esa.esoc.events",
            "@xmlns:ems":"http://esa.esoc.ems",
            "header": { "format_version":"1", "generation_time":"2022-222222",
                "validity_start": "202201028208018",
                "validity_end": "popop",
                "spacecraft": "hasbullagodsupremewewilldoit",
                "icd_version": "PROBA3-1.0",
            },
            "events": {'bot_info': {'@time': '2022-05-01T16:20:01Z', '@TM_RATE': 'HBR'},
                       'start_ul': {'@time': '2022-05-02T17:20:01Z', '@SPACECRAFT': 'OSC'},
            }
        }
    })

print(xmltodict.unparse(mydict, indent=" ", pretty=True, newl='\n'))

image version: code

To identify an attribute the symbol '@' is used, but the attributes are displayed only on the same line, not in separate lines like in the example file I provided above.

My output looks like this:

<?xml version="1.0" encoding="utf-8"?>
<eventfile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://esa.esoc.eventsgen_event_sample.xsd xmlns:http://esa.esoc.events" xmlns:ems="http://esa.esoc.ems">
 <header>
  <format_version>1</format_version>
  <generation_time>2022-222222</generation_time>
  <validity_start>202201028208018</validity_start>
  <validity_end>popop</validity_end>
  <spacecraft>hasbullagodsupremewewilldoit</spacecraft>
  <icd_version>PROBA3-1.0</icd_version>
 </header>
 <events>
  <bot_info time="2022-05-01T16:20:01Z" TM_RATE="HBR"></bot_info>
  <start_ul time="2022-05-02T17:20:01Z" SPACECRAFT="OSC"></start_ul>
 </events>
</eventfile>

image version: output

I also tried with the ElementTree library, but still I couldn't find a solution.

Do you have any suggestions?

Thank you.

0

There are 0 answers