原文链接: python dict转xml

代码

1
2
3
4
5
6
7
8
9
10
11
import dicttoxml
from xml.dom.minidom import parseString
d = {'k':[{'k1':'v1'}, {'k2':'v2', 'k3':'v3'}]}
#xml = dicttoxml.dicttoxml(d, attr_type=False, root=True)
xml = dicttoxml.dicttoxml(d, attr_type=False, root=False)
print(xml)
dom = parseString(xml)
xml = dom.toprettyxml()
print(xml)

输出

1
2
3
4
5
6
7
8
9
10
11
b'<k><item><k1>v1</k1></item><item><k3>v3</k3><k2>v2</k2></item></k>'
<?xml version="1.0" ?>
<k>
<item>
<k1>v1</k1>
</item>
<item>
<k3>v3</k3>
<k2>v2</k2>
</item>
</k>

dicttoxml, https://github.com/quandyfactory/dicttoxml
attr_type, Each element includes an optional type attribute with the data type.
xml.dom.minidom.parseString(xml).toprettyxml(), return a pretty-printed version of the document.