How to generate XML using Python?

PythonProgramming

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>
raja
Published on 20-Apr-2018 07:15:45
Advertisements