如何使用 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