XML
  Home arrow XML arrow Page 6 - Parsing XML with SAX and Python
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Parsing XML with SAX and Python
By: Nadia Poulou
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 36
    2004-11-09

    Table of Contents:
  • Parsing XML with SAX and Python
  • The xml.sax Package
  • Our SAX Parser
  • The Heart of the Code
  • Element Content
  • The Main Code
  • Homework

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Parsing XML with SAX and Python - The Main Code


    (Page 6 of 7 )

     

    The following snippet gets the player name from the playerName field of the form:

    FormData = cgi.FieldStorage()
    searchTerm= FormData["playerName"].value

    Now that we have our search term, let’s initiate our parser and handler objects:

    parser = make_parser()   
    curHandler = BasketBallHandler(searchTerm)

    With the help of the method setContentHandler(), we connect the implementation of the ContentHandler to our reader instance as it is shown here:

    parser.setContentHandler(curHandler)

    Finally we parse our XML document:

    parser.parse(open('playerStats.xml'))

    Here I paste the code of the finished script as a reference:

    #!/usr/bin/python"

    print "Content-Type: text/plain\n"   
    print "<html><body>"

    from xml.sax import make_parser
    from xml.sax.handler import ContentHandler
    import cgi

    class BasketBallHandler(ContentHandler):

     def __init__ (self, searchTerm):
       self.searchTerm= searchTerm;
       self.isPointsElement, self.isReboundsElement = 0, 0;
       
     def startElement(self, name, attrs):

       if name == 'player':     
         self.playerName = attrs.get('name',"")
         self.playerAge = attrs.get('age',"")
         self.playerHeight = attrs.get('height',"")
       elif name == 'points':
         self.isPointsElement= 1;
         self.playerPoints = "";
       elif name == 'rebounds':
         self.isReboundsElement = 1;
         self.playerRebounds = "";
       return

     def characters (self, ch):
       if self.isPointsElement== 1:
         self.playerPoints += ch
       if self.isReboundsElement == 1:
         self.playerRebounds += ch

     def endElement(self, name):
       if name == 'points':
         self.isPointsElement= 0
       if name == 'rebounds':
         self.inPlayersContent = 0
       if name == 'player' and self.searchTerm== self.playerName :
           print '<h2>Statistics for player:' , self.playerName, '</h2><br>(age:', self.playerAge , 'height' , self.playerHeight , ")<br>"
           print 'Match average:', self.playerPoints , 'points,' , self.playerRebounds, 'rebounds'

    FormData = cgi.FieldStorage()
    searchTerm= FormData["playerName"].value
    parser = make_parser()   
    curHandler = BasketBallHandler(searchTerm)
    parser.setContentHandler(curHandler)
    parser.parse(open('playerStats.xml'))
    print "</body></html>"

    More XML Articles
    More By Nadia Poulou


       · Nice article. The correct URL for Uche Ogbuji's site...
       · I'm new to all of this and found this article to be a tremendous help. Thanks so...
       · Thanks for this great article. I have a question. I am using your code to learn xml...
       · Thank you for this article. Very easy, ideas very well exposed. The code have...
       · Thanks. This was exactly what I was looking for and explained things very nicely...
     

    XML ARTICLES

    - Using Regions with XSL Formatting Objects
    - Using XSL Formatting Objects
    - More Schematron Features
    - Schematron Patterns and Validation
    - Using Schematron
    - Datatypes and More in RELAX NG
    - Providing Options in RELAX NG
    - An Introduction to RELAX NG
    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek