How to convert lists to XML in Python? - GeeksforGeeks

24 Jan, 2021
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 listsCreate the root element as “userconfig”Create sub-elementsInsert list entries into sub-elementWrite the tree into an XML file
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 subtreeimport 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 fileroot = minidom.Document()   # creat root elementxml = 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 filesave_path_file = "gfg.xml"  with open(save_path_file, "w") as f:     f.write(xml_str) 
Output:
Picked
Python-XML
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()