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.
- <data>
- <contact id="1">
- <name>john doe</name>
- <address>unknown</address>
- <phone>007</phone>
- </contact>
- <contact id="2">
- <name>Test2</name>
- <address>Test Address2</address>
- <phone>1002</phone>
- </contact>
- </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
- myroot=''
- def setXml(root,tree):
- global myroot
- global mytree
- myroot=root
- mytree=tree
-
- def readContact():
- global myroot
- for contact in myroot.findall('contact'):
- contactId=contact.attrib['id']
- name=contact.find('name').text
- address=contact.find('address').text
- phone=contact.find('phone').text
- print(" Name =",name,"\n"," Address =",address,"\n",
- " Phone =",phone,"\n"," Id =",contactId)
- print("----------------------------")
- input("Press any key to continue...")
-
- def getId():
- global myroot
- temp = 0
- for contact in myroot.findall('contact'):
- id= int(contact.attrib['id'])
- if id>temp:
- temp=id
- return temp+1
-
- def newContact(ET):
- global myroot
- global mytree
- print("Create a record")
- name=input("Name:")
- address=input("Address:")
- phone=input("Phone:")
- nextId=getId()
- newrecord = ET.SubElement(myroot, "contact",id=str(nextId))
- ET.SubElement(newrecord, "name", name="name").text = name
- ET.SubElement(newrecord, "address", name="address").text = address
- ET.SubElement(newrecord, "phone", name="phone").text = phone
- mytree.write("contact.xml")
- print("Contact created...")
-
- def deleteContact():
- global myroot
- global mytree
- deleteRecord=int(input("Enter the id of the contact you want to delete: "))
-
- for contact in myroot.findall('contact'):
- delid= int(contact.attrib['id'])
- if delid == deleteRecord:
- myroot.remove(contact)
- mytree.write("contact.xml")
- print("Contact deleted...")
-
- def updateContact():
- global myroot
- global mytree
- updateRecord=int(input("Enter the id of contact you want to update: "))
- for contact in myroot.findall('contact'):
- upid= int(contact.attrib['id'])
- if upid == updateRecord:
-
- name = contact.find('name').text
- address = contact.find('address').text
- phone = contact.find('phone').text
-
- name = input("Please enter name:") or name
- contact.find('name').text= name
- address = input("Please enter address:") or address
- contact.find('address').text= address
- phone = input("Please enter phone:") or phone
- contact.find('phone').text= phone
- mytree.write("contact.xml")
- print("Contact updated...")
-
myxml.py
- import xml.etree.ElementTree as ET
- import sys
-
- import mymodules as myfun
- try:
- mytree = ET.parse('contact.xml')
- myroot = mytree.getroot()
- choice=int(input('What you want to do..?\n 1.List\n 2.Insert \n 3.Update \n 4.Delete \n'))
- myfun.setXml(myroot,mytree)
-
- myfun.newContact(ET) if choice ==2 else ""
- myfun.updateContact() if choice ==3 else ""
- myfun.deleteContact() if choice ==4 else ""
- myfun.readContact() if choice ==1 else ""
- except OSError as err:
- print("OS error: {0}".format(err))
- except:
- print("Unexpected error:", sys.exc_info()[0])
- raise
Step 3
Run the myxml.py in the terminal. The screenshot of output as in vscode is as below.