Skip to content

Instantly share code, notes, and snippets.

@haseeb-heaven
Created May 26, 2022 15:36
Show Gist options
  • Save haseeb-heaven/9a5d1c6e7e3d0a60ae3c096c5b17a4bf to your computer and use it in GitHub Desktop.
Save haseeb-heaven/9a5d1c6e7e3d0a60ae3c096c5b17a4bf to your computer and use it in GitHub Desktop.
XML Parsers collection using Element Tree and BeautifulSoup.
"""
Info: XML Parser using Element Tree and BeautifulSoup.
Author: Haseeb Mir.
Date: 05/26/2022
"""
#Import the Package modules.
import xml.etree.ElementTree as xml
from bs4 import BeautifulSoup
#XML Users data file.
users_file = 'Users.xml'
#Read file with exception handling.
def read_file(filename:str,lines:bool=False,mode:str='r'):
data = ""
try:
fp = open(filename,mode=mode)
if not lines:
data = fp.read()
else:
data = fp.readlines()
fp.close()
except Exception as e:
print("Exception occured : " + str(e))
return data
#XML Parser using Element Tree. Returns root element if found.
def xml_parser(xml_file:str,xml_root:str):
try:
tree = xml.parse(xml_file)
root = tree.getroot()
root_element = root.findall(xml_root)
return root_element
except Exception as e:
print("Exception occured while parsing: " + str(e))
#XML Parser using Element beautifulSoup. Returns root element if found.
def xml_parser_soup(xml_file:str,xml_root:str):
try:
contents = read_file(xml_file)
soup = BeautifulSoup(contents, 'xml')
root_element = soup.find_all(xml_root)
return root_element
except Exception as e:
print("Exception occured while parsing: " + str(e))
#Main Method.
if __name__ == '__main__':
try:
#Get the data from XML parser.
users = xml_parser(users_file,'user')
#Iterate through root element.
for user in users:
print(user.find('country').text)
print(user.find('city').text)
except Exception as e:
print("Exception occured : " + str(e))
@haseeb-heaven
Copy link
Author

haseeb-heaven commented May 26, 2022

Users.xml file:

<users-info>

<user>

<name>Abdul</name>

<city>London</city>

<country>England</country>

</user>

<user>

<name>Ahmed</name>

<city>Istanbul</city>

<country>Turkey</country>

</user>

<user>

<name>Mohammed</name>

<city>Cairo</city>

<country>Egypt</country>

</user>

</users-info>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment