Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dicttoxml same key multiple times

I am trying to do xml that looks like:

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

using python dicttoxml lib

tried:

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

but got bad xml not as excepted. Thanks for help!

like image 714
Lior Pozin Avatar asked Sep 19 '26 08:09

Lior Pozin


1 Answers

You can create a dictionary with a repeating key by wrapping the keys with a dummy class and then use dicttoxml on that dictionary. Use collections.OrderedDict if the order matters:

from dicttoxml import dicttoxml
from collections import OrderedDict

class Node(object):
    def __init__(self, name):
        self._name = name

    def __str__(self):
        return self._name

quest_dict = OrderedDict([(Node('key1'), 'aaa'), (Node('key1'), 'bbb'), (Node('key1'), 'ccc')])
request_xml = dicttoxml(quest_dict, attr_type=False, root=False)
print(request_xml)

This gives your desired output:

b'<key1>aaa</key1><key1>bbb</key1><key1>ccc</key1>'
like image 120
Dave Reikher Avatar answered Sep 21 '26 21:09

Dave Reikher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!