Converting an array dict to xml in python?

前端 未结 3 1234
轮回少年
轮回少年 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:17

    I ended up taking the solution from here, then adding a for-loop over the elements in your array. The output uses attributes instead of elements like you had asked, though.

    Full code outside of that function is this. I ended up using regex to strip out the intermediate tags, then placed the on the outside at the end.

    import re 
    
    array = [
        {
            'time': {"hour":"1", "minute":"30","seconds": "40"}
        },
        {
            'place': {"street":"40 something", "zip": "00000"}
        }
    ]
    
    xml_title = "test"
    xml_tag_pattern = re.compile(r''.format(xml_title))
    inner_xml = re.sub(xml_tag_pattern, '', ''.join(dict2xml(e, root_node=tag_name) for e in array))
    
    print('<{0}>{1}'.format(xml_title, inner_xml))
    

    The output is this (new lines added for clarity)

    
        
    

提交回复
热议问题