Jam Jam - 3 months ago 61
Python Question

How to flatten XML file in Python

Is there a library or mechanism I can use to flatten the XML file?

Existing:

<A>
<B>
<ConnectionType>a</ConnectionType>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:00</EndTime>
<UseDataDictionary>N</UseDataDictionary>


Desired:

A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N

Answer

By using xmltodict to transform your XML file to a dictionary, in combination with this answer to flatten a dict, this should be possible.

Example:

# Original code: http://codereview.stackexchange.com/a/21035
from collections import OrderedDict

def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
                for subkey, subvalue in flatten_dict(value).items():
                    yield key + "." + subkey, subvalue
            else:
                yield key, value

    return OrderedDict(items())

import xmltodict

# Convert to dict
with open('test.xml', 'rb') as f:
    xml_content = xmltodict.parse(f)

# Flatten dict
flattened_xml = flatten_dict(xml_content)

# Print in desired format
for k,v in flattened_xml.items():
    print('{} = {}'.format(k,v))

Output:

A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N
Comments