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">

<student branch="IT">

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.


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:


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.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":
      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": = 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()


_________________student Details_________________
Roll Number=201610231
_________________student Details_________________
Roll Number=201610331

You may also read,

Leave a Reply

Your email address will not be published. Required fields are marked *