您可以使用dicttoxml 方法的custom_root 和item_func 参数获取您期望的xml:
import dicttoxml
request_dict = ['aaa', 'bbb', 'ccc']
item_name = lambda x: 'key1'
request_xml = dicttoxml.dicttoxml(request_dict, attr_type=False, custom_root='xml', item_func=item_name)
print(request_xml.decode('utf-8'))
输出:
<xml><key1>aaa</key1><key1>bbb</key1><key1>ccc</key1></xml>
此示例的扩展解决了单个 xml 中多个重复键的情况,如 <xsd:element minOccurs="0" maxOccurs="unbounded"> 定义的
我无法使用 Dave 的回答中的 OrderedDict 来实现。最接近的结果是使用 item_func lambda,它以父项的名称命名项目:
import dicttoxml
xml_dict = {}
xml_dict['key1'] = ['aaa', 'bbb', 'ccc']
xml_dict['another-key'] = ['a','b','c']
item_name = lambda x: x
request_xml = dicttoxml.dicttoxml(xml_dict, attr_type=False, custom_root='xml', item_func=item_name)
print(request_xml.decode('utf-8'))
但是我们必须从结果中删除父母:
<xml>
<key1>
<key1>aaa</key1>
...
可以应用清理(显式):
xml_str = request_xml.decode("utf-8", "strict")
xml_str = xml_str.replace('<key1><key1>', '<key1>').replace('</key1></key1>', '</key1>')
xml_str = xml_str.replace('<another-key><another-key>', '<another-key>').replace('</another-key></another-key>', '</another-key>')
print(xml_str)
结果:
<xml>
<key1>aaa</key1>
...
<another-key>a</another-key>
...
</xml>