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

開啟您的職業生涯

透過完成此課程獲得認證

開始學習
廣告
© . All rights reserved.