Converting an array dict to xml in python?

前端 未结 3 1221
轮回少年
轮回少年 2021-02-13 18:53

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

array = [
    {
        \'time\': {\"hour\":\"1\", \"minute\":\"30\",\"seconds\": \"40\"}
    },
    {
        \         


        
3条回答
  •  执笔经年
    2021-02-13 18:58

    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''
        return xml
    

    Examples:

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

提交回复
热议问题