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.
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() Function:
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 for Turning a Dictionary into XML:
Python3
from xml.etree.ElementTree import Element,tostring
def dict_to_xml(tag, d):
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str (val)
elem.append(child)
return elem
s = { 'name' : 'geeksforgeeks' ,
'city' : 'noida' , 'stock' : 920 }
e = dict_to_xml( 'company' , s)
print (e)
print (tostring(e))
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>’