Python CRUD Operations With XML File

Introduction

In this blog, we will learn how to perform basic CRUD application using Python and an XML file. We will also learn how to create a Python module and use it. 

Prerequisite

VS Code or any other IDE for development.

Step 1
 
Create an XML file. Here, I have created a contact.xml with the following structure.
  1. <data>  
  2.     <contact id="1">  
  3.         <name>john doe</name>  
  4.         <address>unknown</address>  
  5.         <phone>007</phone>  
  6.     </contact>  
  7.     <contact id="2">  
  8.         <name>Test2</name>  
  9.         <address>Test Address2</address>  
  10.         <phone>1002</phone>  
  11.     </contact>  
  12. </data>  

Step 2

Creating Python module for CRUD operations.We will be using Python xml.etree.ElementTree module for creating and reading  the XML data. I have created two files - myxml.py which is the application file and mymodules.py which has all functions of CRUD. We will import mymodules.py in our application file. I have included comments in the code for better understanding. The code is as below,
 
mymodules.py
  1. myroot=''  
  2. def setXml(root,tree):  
  3.     global myroot  
  4.     global mytree  
  5.     myroot=root  
  6.     mytree=tree  
  7. # Function to list all xml elements      
  8. def readContact():  
  9.     global myroot  
  10.     for contact in myroot.findall('contact'):  
  11.         contactId=contact.attrib['id']  
  12.         name=contact.find('name').text  
  13.         address=contact.find('address').text  
  14.         phone=contact.find('phone').text  
  15.         print("  Name =",name,"\n"," Address =",address,"\n",  
  16.         " Phone =",phone,"\n"," Id =",contactId)  
  17.         print("----------------------------")  
  18.     input("Press any key to continue...")      
  19. # Function to return next element id          
  20. def getId():  
  21.     global myroot  
  22.     temp = 0  
  23.     for contact in myroot.findall('contact'):  
  24.         id= int(contact.attrib['id'])  
  25.         if id>temp:  
  26.             temp=id  
  27.     return temp+1       
  28. # Function to create a new element         
  29. def newContact(ET):  
  30.     global myroot  
  31.     global mytree  
  32.     print("Create a record")  
  33.     name=input("Name:")  
  34.     address=input("Address:")  
  35.     phone=input("Phone:")          
  36.     nextId=getId()  
  37.     newrecord = ET.SubElement(myroot, "contact",id=str(nextId))  
  38.     ET.SubElement(newrecord, "name", name="name").text = name  
  39.     ET.SubElement(newrecord, "address", name="address").text = address  
  40.     ET.SubElement(newrecord, "phone", name="phone").text = phone  
  41.     mytree.write("contact.xml")    
  42.     print("Contact created...")  
  43. # Function to delete a element          
  44. def deleteContact():  
  45.     global myroot  
  46.     global mytree  
  47.     deleteRecord=int(input("Enter the id of the contact you want to delete: "))  
  48.     #loop through all id's  
  49.     for contact in myroot.findall('contact'):  
  50.         delid= int(contact.attrib['id'])  
  51.         if delid == deleteRecord:  
  52.             myroot.remove(contact)              
  53.             mytree.write("contact.xml")  
  54.             print("Contact deleted...")      
  55. # Function to update a element  
  56. def updateContact():  
  57.     global myroot  
  58.     global mytree  
  59.     updateRecord=int(input("Enter the id of contact you want to update: "))  
  60.     for contact in myroot.findall('contact'):  
  61.         upid= int(contact.attrib['id'])  
  62.         if upid == updateRecord:  
  63.             #first we will select all current values  
  64.             name = contact.find('name').text  
  65.             address = contact.find('address').text  
  66.             phone = contact.find('phone').text  
  67.            #update..the or input means if input is empty keep old value  
  68.             name = input("Please enter name:"or name  
  69.             contact.find('name').text= name  
  70.             address = input("Please enter address:"or address  
  71.             contact.find('address').text= address  
  72.             phone = input("Please enter phone:"or phone  
  73.             contact.find('phone').text= phone  
  74.             mytree.write("contact.xml")  
  75.             print("Contact updated...")  
  76.               
myxml.py
  1. import xml.etree.ElementTree as ET   
  2. import sys  
  3. #importing module we created as myfun  
  4. import mymodules as myfun  
  5. try:  
  6.     mytree = ET.parse('contact.xml'
  7.     myroot = mytree.getroot()  
  8.     choice=int(input('What you want to do..?\n 1.List\n 2.Insert \n 3.Update \n 4.Delete \n'))  
  9.     myfun.setXml(myroot,mytree)  
  10.     #using python conditional statement..calls function according to choice  
  11.     myfun.newContact(ET) if choice ==2 else ""  
  12.     myfun.updateContact() if choice ==3 else ""     
  13.     myfun.deleteContact() if choice ==4 else ""  
  14.     myfun.readContact() if choice ==1 else ""     
  15. except OSError as err:  
  16.     print("OS error: {0}".format(err))  
  17. except:  
  18.     print("Unexpected error:", sys.exc_info()[0])  
  19.     raise  

Step 3

Run the myxml.py in the terminal. The screenshot of output as in vscode is as below.
 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now