import xml.etree.ElementTree as ET def parse_dict_to_xml(_root, data): for key, val in data.items(): child = ET.SubElement(_root, key) if isinstance(val, str) or isinstance(val, int) or isinstance(val, float): child.text = str(val) else: parse_dict_to_xml(child, val) return _root def get_xml(_data): root = ET.Element('root') xml_data = parse_dict_to_xml(root, _data) xml_str = ET.tostring(xml_data, encoding='utf8', method='xml') return xml_str if __name__ == '__main__': # failed_resp_data = {'url': '请检查foramt、pid参数', 'sig': ''} # root = ET.Element('root') # xml_data = parse_dict_to_xml(root, failed_resp_data) # xml_str = ET.tostring(xml_data, encoding='utf8', method='xml') # print(xml_str) pass