How to convert lists to XML in Python?
Last Updated :
25 Jan, 2023
In this article, the task is to convert a given list to XML in Python. But first, let's discuss what is an XML?
It could also be terminology that defines a gaggle of rules for encoding documents during a format that's both human-readable and machine-readable. The design goals of XML specialize in simplicity, generality, and usefulness across the web. It is a textual format with strong support via Unicode for various human languages.
You can refer to the article Create XML Documents using Python for further information.
Method 1: Using Element tree
Python features a built-in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files). ElementTree represents the whole XML document as a tree that helps while performing the operations. The element represents a single node in this tree. Reading and writing from the whole document are done on the ElementTree level. Interactions with one XML element and its sub-elements are done on the Element level. Refer: Modify XML files with Python
import xml.etree.ElementTree as ET
XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >.
Approach Used :
- Use ElementTree to insert items of lists
- Create the root element as “userconfig”
- Create sub-elements
- Insert list entries into sub-element
- Write the tree into an XML file
Python3
# Firstly we have to import 'xml.etree.ElementTree' for creating a subtree
import xml.etree.ElementTree as ET
users_list = ["GeeksForGeeks", "Arka", "Computer Science", "Engineering", "Portal"]
def create_xml():
# we make root element
usrconfig = ET.Element("usrconfig")
# create sub element
usrconfig = ET.SubElement(usrconfig, "usrconfig")
# insert list element into sub elements
for user in range(len( users_list)):
usr = ET.SubElement(usrconfig, "usr")
usr.text = str(users_list[user])
tree = ET.ElementTree(usrconfig)
# write the tree into an XML file
tree.write("Output.xml", encoding ='utf-8', xml_declaration = True)
create_xml()
Output:

Method 2: Using xml.dome
The xml.dom.minidom module provides an easy parser for creating DOM trees. DOM (document object model) may be a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the assistance of xml.dom.minidom, which is that the minimal implementation of the DOM interface. It is simpler than the complete DOM API and will be considered as smaller.
For further reference of the given library, visit Parse XML using Minidom in Python.
Python3
from xml.dom import minidom
import os
users_list = ["GeeksForGeeks", "Arka", "Computer Science", "Engineering", "Portal"]
# create file
root = minidom.Document()
# create root element
xml = root.createElement('root')
root.appendChild(xml)
for user in range(len( users_list)):
# create child element
productChild = root.createElement('product'+ str(user))
# insert user data into element
productChild.setAttribute('list', users_list[user] )
xml.appendChild(productChild)
xml_str = root.toprettyxml(indent ="\t")
# save file
save_path_file = "gfg.xml"
with open(save_path_file, "w") as f:
f.write(xml_str)
Output:

Similar Reads
Convert Tuple to List in Python In Python, tuples and lists are commonly used data structures, but they have different properties:Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for furt
2 min read
Convert XML to CSV in Python XML (Extensible Markup Language) is widely used to store and transport structured data. However, for tasks like data analysis or spreadsheet editing, CSV (Comma-Separated Values) is far more user-friendly and easier to work with.To make XML data easier to process, we often convert it to a CSV file.
2 min read
How to Convert Excel to XML Format in Python? Python proves to be a powerful language when the requirement is to convert a file from one format to the other. It supports tools that can be employed to easily achieve the functionality. In this article, we'll find out how we will convert from an Excel file to Extensible terminology (XML) files wit
3 min read
Convert string to a list in Python Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read
How to Convert XML to CSV in R? Converting data from XML to CSV format can be a handy skill, especially when you need to work with data in a more accessible format like CSV. Here, we'll discuss about the process of converting XML files to CSV using R programming language for data analysis.What is XML (eXtensible Markup Language)?X
4 min read
How to convert NumPy array to list ? This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding. Convert NumPy Array to List There are various ways to convert NumPy Array to List here we are discussing some generally us
4 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 H
4 min read
How to Convert XML to DataFrame in R? A Data Frame is a two-dimensional and tabular data structure in the R that is similar to a table in the database or an Excel spreadsheet. It is one of the most commonly used data structures for the data analysis in R with the columns representing the various and rows representing the observations.XM
4 min read
Python - Converting list string to dictionary Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val
3 min read
Python - Convert list of string to list of list In Python, we often encounter scenarios where we might have a list of strings where each string represents a series of comma-separated values, and we want to break these strings into smaller, more manageable lists. In this article, we will explore multiple methods to achieve this. Using List Compreh
3 min read