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

更新於:2020-03-05

1K+ 瀏覽量

開啟你的 職業生涯

完成課程後獲得認證

開始學習
廣告