The Wayback Machine - https://web.archive.org/web/20240717024743/https://www.geeksforgeeks.org/turning-a-dictionary-into-xml-in-python/
Open In App

Turning a Dictionary into XML in Python

Last Updated : 01 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# import Element 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>’ 
 



Similar Reads

Turning a Function Pointer to Callable
Well, the memory address of a compiled function is obtained but how to turn it to Python callable that can be used as an extension. The answer to this the use of ctypes module that can create a Python callable and can wrap arbitrary memory address. The code below shows how to obtain the raw, low-level address of a C function and how to turn it back
2 min read
MoviePy – Turning on auto play for video clip file
In this article we will see how we can turn on the auto play of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can display a video with the help of ipyt
2 min read
Python program to convert XML to Dictionary
In this article, we will discuss how to convert an XML to a dictionary using Python. Modules Usedxmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module. Syntax: pip install xmltodict pprint: The pprint module provides a capability to “pretty
2 min read
Serialize Python dictionary to XML
XML is a markup language that is designed to transport data. It was made while keeping it self descriptive in mind. Syntax of XML is similar to HTML other than the fact that the tags in XML aren't pre-defined. This allows for data to be stored between custom tags where the tag contains details about the data and the data is stored in between the op
5 min read
How to store XML data into a MySQL database using Python?
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is o
3 min read
Adding Data into Existing XML File in Python
We are given an XML existing file and our task is to append new data into that existing XML using Python. In this article, we will see how we can append new data to the existing XML using Python. Creating an XML fileIn this example, an XML tree is constructed using the xml.etree.ElementTree module in Python, where child elements with attributes and
3 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Create XML Documents using Python
Extensible Markup Language(XML), is a markup language that you can use to create your own tags. It was created by the World Wide Web Consortium (W3C) to overcome the limitations of HTML, which is the basis for all Web pages. XML is based on SGML - Standard Generalized Markup Language. It is used for storing and transporting data. XML doesn’t depend
3 min read
How to Parse and Modify XML in Python?
XML stands for Extensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet. Note: For more information, refer to XML | Basics Here we consider that the XML file is present in th
4 min read
Python - JSON to XML
A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON
5 min read
Practice Tags :
three90RightbarBannerImg