How to fetch XML data in python?
XML stands for Extensible Markup language. now I am going to show you how to fetch XML data using python programming.
Here I will show your extracting data from XML with an easy example.
First, I will have to create an XML file (student.xml)which contains some information data, that data going to be fetched by python code.
<college type="engineering"> <student branch="CSE"> <name>raj</name> <rollno>201610231</rollno> <address>patna</address> </student> <student branch="IT"> <name>prakash</name> <rollno>201610331</rollno> <address>Odisha</address> </student> </college>
now to fetch the data we have to import a package in python :
import xml.sax
xml.sax package provides various module for simple API for XML (SAX) .
now for parsing XMl, there is a requirement of ContentHandler. which is used to handle the particular tags and attributes of XML.
The make_parser Method
the make_parser method is used to create an xmlReader to read the data from the xml file.
xml.sax.make_parser([list])
list: consisting of a list of a parser.
now we also used another method for creating a SAX parser and uses to parse a document:
xml.sax.parse(xmlfile,contenthandler,errorhandler)
Arguments details:
xmlfile:name of XML file.
contenthandler: Object of the content handler.
errorhandler: SAX error handler.
python code for fetching XML data ( using class and functions )
import xml.sax
class Students( xml.sax.ContentHandler ):
def _init_(self):
self.CurrentData = ""
self.name = ""
self.rollno = ""
self.address = ""
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "college":
print "___________________Student Details_____________________"
branch = attributes["branch"]
print("Branch=", branch)
def endElement(self, tag):
if self.CurrentData == "name":
print("Name=", self.name)
elif self.CurrentData == "rollno":
print("Roll Number=", self.rollno)
elif self.CurrentData == "address":
print("Address=", self.address)
self.CurrentData = ""
def characters(self, content):
if self.CurrentData == "name":
self.name = content
elif self.CurrentData == "rollno":
self.rollno = content
elif self.CurrentData == "address":
self.address = content
if ( _name_ == "_main_"):
# create an XMLReader to read the data from xml file.
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
#Object of Students class.
H= Students()
parser.setContentHandler(H)
parser.parse("student.xml")Output:
_________________student Details_________________ Branch=CSE Name=raj Roll Number=201610231 Address=patna _________________student Details_________________ Branch=IT Name=prakash Roll Number=201610331 Address=odisha
You may also read,
Leave a Reply