如何使用 Python 生成 XML?
要从 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>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP