How to generate XML using Python?


To generate XML from a python dictionary, you need to install the dicttoxml package. You can install it using −

$ pip install dicttoxml

Once installed, you can use the dicttoxml method to create the xml. 

example

a = {
   'foo': 45,
   'bar': {
      'baz': "Hello"
   }
}
xml = dicttoxml.dicttoxml(a)
print(xml)

Output

This will give the output −

b'<?xml version="1.0" encoding="UTF-8" ?><root><foo type="int">45</foo><bar type="dict"><baz type="str">Hello</baz></bar></root>'

You can also prettyprint this output using the toprettyxml method. 

example

from xml.dom.minidom import parseString
a = {
   'foo': 45,
   'bar': {
      'baz': "Hello"
   }
}
xml = dicttoxml.dicttoxml(a)
dom = parseString(xml)
print(dom.toprettyxml())

Output

This will give the output −

<?xml version = "1.0" ?>
<root>
   <foo type = "int">45</foo>
   <bar type = "dict">
      <baz type = "str">Hello</baz>
   </bar>
</root>

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements