Skip to content
Related Articles

Related Articles

Turning a Dictionary into XML in Python
  • Last Updated : 24 Jul, 2020

XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element called as the root element.

Example: 

<geeksforgeeks>
<course>DSA</course>
<price>2499/-</price>
</geeksforgeeks>

In the above example, geeksforgeeks is the root element and <course>, <price>, <price> are the elements.

Now, let’s see how to Turn a Dictionary into XML:
For turning a Dictionary into XML in Python we will use xml.etree.ElementTree library. The xml.etree.ElementTree library is usually used for parsing and also utilised in creating XML documents. The ElementTree class is employed to wrap a component structure and convert it from and to XML. The result of this conversion is an Element. For I/O, it’s easy to convert this to a byte string using the tostring() function in xml.etree.ElementTree.

xml.etree.ElementTree.Element() Class:

This Element class defines the Element interface, and provides a reference implementation of this interface. 
 



Syntax: Element(tag, attrib = {}, **extra)

Parameter: 

  •  tag: This is a string that identify what kind of data this element represents.
  •  attrib: this is an optional dictionary, containing element attributes.
  •  **extra: This contains additional attributes, given as keyword arguments.

Return: Element object

xml.etree.ElementTree.tostring() Functon:

This function Generates a string representation of an XML element. 

Syntax: tostring(element)

Parameter: XML element

Return: string representation of an XML element

ElementObject.set() Method:

This method Set the attribute key on the element to value. 
 



Syntax: set(key, value)

Parameter: 

  •  key: represent the attribute.  
  •  value: represent value of attribute.

Return: None

Now, let’s see the python program fro Turning a Dictionary into XML:

python3




# import Elment class, tostring function
# from xml.etree.ElementTree library
from xml.etree.ElementTree import Element,tostring
  
# define a function to 
# convert a simple dictionary 
# of key/value pairs into XML
def dict_to_xml(tag, d):
  
    elem = Element(tag)
    for key, val in d.items():
        # create an Element
        # class object
        child = Element(key)
        child.text = str(val)
        elem.append(child)
          
    return elem
  
# Driver Program
s = { 'name': 'geeksforgeeks',
     'city': 'noida', 'stock': 920 }
  
# e stores the element instance
e = dict_to_xml('company', s)
  
# Element instance is different 
# every time you run the code 
print(e)
  
# converting into a byte string
print(tostring(e))
  
# We can attach attributes 
# to an element using 
# set() method
e.set('_id','1000')
  
print(tostring(e))

Output: 

<Element ‘company’ at 0x7f411a9bd048>
b'<company><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’
b'<company _id=”1000″><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :