python dicttoxml多次使用相同的密钥

时间:2016-06-20 21:49:20

标签: python xml python-2.7

我正在尝试做看起来像的xml:

<xml....
<key1>aaa </key1>
<key1>bbb</key1>
<key1>ccc</key1>
</xml>

使用python dicttoxml lib

尝试:

quest_dict = [{'key1': 'aaa'}, {'key1': 'bbb'}, {'key1': 'ccc'}]
request_xml = dicttoxml.dicttoxml(request_dict, attr_type=False, root=False)

但是坏的xml不是例外。 谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

您可以通过使用虚拟类包装键来创建包含重复键的字典,然后在该字典上使用dicttoxml。如果订单很重要,请使用collections.OrderedDict

b'<key1>aaa</key1><key1>bbb</key1><key1>ccc</key1>'

这会得到您想要的输出:

li_attr

答案 1 :(得分:0)

您可以使用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>