Open In App

How to convert lists to XML in Python?

Last Updated : 25 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

  1. Use ElementTree to insert items of lists
  2. Create the root element as “userconfig”
  3. Create sub-elements
  4. Insert list entries into sub-element
  5. 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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads