Turning a Dictionary into XML in Python

01 Sep, 2021
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 utilized 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.
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 
This function Generates a string representation of an XML element. 
Syntax: tostring(element)
Parameter: XML element
Return: string representation of an XML element
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 for Turning a Dictionary into XML:
Python3
# import Element class, tostring function# from xml.etree.ElementTree libraryfrom xml.etree.ElementTree import Element,tostring # define a function to# convert a simple dictionary# of key/value pairs into XMLdef 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 Programs = { 'name': 'geeksforgeeks',     'city': 'noida', 'stock': 920 } # e stores the element instancee = dict_to_xml('company', s) # Element instance is different# every time you run the codeprint(e) # converting into a byte stringprint(tostring(e)) # We can attach attributes# to an element using# set() methode.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>’  
clintra
kalrap615
sumitgumber28
python-modules
Python-XML
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python