Converting an array dict to xml in python?

Viewed 50623

I have this array that I need to convert to xml.

array = [
    {
        'time': {"hour":"1", "minute":"30","seconds": "40"}
    },
    {
        'place': {"street":"40 something", "zip": "00000"}
    }
]

The xml should have a title that I can put in as a variable for example,

xml_title = "test"

The result I want based on the array above and the xml title is this:

<test>
    <time hour="1" minute="30" second="40"></time>
    <place>
        <street>40 something</street>
        <zip>00000</zip>
    </place>
</test>

I liked the answer given in a similar stack overflow question (https://stackoverflow.com/a/18991263/875139) but I am confused how I can use that answer to get this desired result.

Help please.

3 Answers

For simple cases, you can go with something like this:

def object_to_xml(data: Union[dict, bool], root='object'):
    xml = f'<{root}>'
    if isinstance(data, dict):
        for key, value in data.items():
            xml += object_to_xml(value, key)

    elif isinstance(data, (list, tuple, set)):
        for item in data:
            xml += object_to_xml(item, 'item')

    else:
        xml += str(data)

    xml += f'</{root}>'
    return xml

Examples:

xml = object_to_xml([1, 2, 3], 'root')
# <root><item>1</item><item>2</item><item>3</item></root>
xml = object_to_xml({"name": "the matrix", "age": 20, "metadata": {"dateWatched": datetime.datetime.now()}}, 'movie')
# <movie><name>the matrix</name><age>20</age><metadata><dateWatched>2020-11-01 00:35:39.020358</dateWatched></metadata></movie>
Related