如何使用 Python 生成 XML?
pythonprogramming更新于 2023/10/30 23:21:00
要从 Python 字典生成 XML,您需要安装 dicttoxml 包。您可以使用 − 安装它
$ pip install dicttoxml
安装后,您可以使用 dicttoxml 方法创建 xml。
示例
a = { 'foo': 45, 'bar': { 'baz': "Hello" } } xml = dicttoxml.dicttoxml(a) print(xml)
输出
将给出输出 −
b'<?xml version="1.0" encoding="UTF-8" ?><root><foo type="int">45</foo><bar type="dict"><baz type="str">Hello</baz></bar></root>'
您还可以使用 toprettyxml 方法漂亮地打印此输出。
示例
from xml.dom.minidom import parseString a = { 'foo': 45, 'bar': { 'baz': "Hello" } } xml = dicttoxml.dicttoxml(a) dom = parseString(xml) print(dom.toprettyxml())
输出
这将给出输出 −
<?xml version = "1.0" ?> <root> <foo type = "int">45</foo> <bar type = "dict"> <baz type = "str">Hello</baz> </bar> </root>