Converting an array dict to xml in python?

前端 未结 3 1222
轮回少年
轮回少年 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 19:18

    As noted in the comments, your original question mixes attributes and elements. If you want everything as elements, you might be able to use dicttoxml. For example:

    from dicttoxml import dicttoxml
    
    array = [
        {
            'time': {"hour":"1", "minute":"30","seconds": "40"}
        },
        {
            'place': {"street":"40 something", "zip": "00000"}
        }
    ]
    
    xml = dicttoxml(array, custom_root='test', attr_type=False)
    

    Produces the following XML:

    
    
        
            
        
        
            
                40 something
                00000
            
        
    
    

    If you can convert your dictionary to:

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

    Then your XML will look as desired.

    
    
        
            40 something
            00000
        
        
    
    

    Note that, in general, the order of dictionary keys are not guaranteed, so if you want to preserve the order of keys in a dict, you may want to check out collections.OrderedDict.

提交回复
热议问题