如何使用 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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP