XML technologies / XML / Python & XML / The Simple API for XML / Reading an article

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

This example shows how to use SAX to extract and use XML information. Our documents are simple news articles, demonstrating elements, attributes and text content.

SAX trade-offs depend on your goal and XML structure. It treats XML as a continuous stream, firing events at your handler as they occur. The next example shows article.xml.

 

Example: article.xml

<?xml version="1.0"?>
<webArticle category="news" subcategory="technical">
  <header title="NASA Builds Warp Drive" length="3k" author="Joe Reporter" distribution="all"/>
  <body>Seattle, WA – Today an anonymous individual announced that NASA has completed building a Warp Drive and has parked a ship that uses the drive in his back yard. This individual claims that although he hasn't been contacted by NASA concerning the parked space vessel, he assumes that he will be launching it later this week to mount an exhibition to the Andromeda Galaxy.</body>
</webArticle>

The example’s differently structured markup makes SAX parsing interesting. For a document like article.xml, understand its structure before writing a handler. The handler is thus tightly coupled to that structure.

Writing a simple handler

Write the class ArticleHandler in a new file called handlers.py. More handlers will be added later. Start simply to see how SAX works:

from xml.sax.handler import ContentHandler

class ArticleHandler(ContentHandler):
    """ Ein Handler für Artikel in XML """
    def startElement(self, name, attrs):
      print "Start-Element:", name

Now create a script to instantiate the parser, assign the handler and do the actual work.

Creating the main program

However complex handlers become, little code is usually needed to set up the parser. The next example uses only the ArticleHandler class just written and parses standard input. The file art.py demonstrates how.

 

Example: art.py

#!/usr/bin/env python
# art.py

import sys

from xml.sax import make_parser
from handlers import ArticleHandler

ch = ArticleHandler( )
saxparser = make_parser( )

saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)

Run the code from the command line using file redirection to supply standard input on Unix or Windows:

 $> python art.py < article.xml 

The simple article handler produces:

Start-Element: webArticle
Start-Element: header
Start-Element: body

This illustrates the class ArticleHandler simply printing each tag name. To use the XML meaningfully, add functionality to the handler in handlers.py.

Adding intelligence

XML information can serve different purposes: one application can display a news article as HTML, another index it in a search database. Imagine a provider’s intelligent agents searching Internet sources for news, offers or other interests based on your preferences. XML enables this, whereas reliably extracting structured information from HTML is nearly impossible. HTML describes appearance, not structure. Two pages can look identical yet use radically different tags. Parsing their information works only if the designer planned for it.

Your agent searches technology news, especially space travel. On finding an article, it shows a notice, headline and first few words. Extend the handler accordingly.

SAX’s streaming nature sometimes requires flags tracking entry into particular elements. If too many flags accumulate, consider a DOM approach instead. SAX excels at many operations on very long streams; complex extracted data structures may suit DOM better.

For simplicity, set a few flags as events arrive and look for the information wanted. In the method startElement, check that you are inside a news article and that it is technical. If both hold, change a Boolean to tell other methods to watch their data. Set a handler variable too, telling the main application it found a technical article—its assigned task:

def startElement(self, name, attrs):
    if name == "webArticle":        
      subcat = attrs.get("subcategory", "")
      if subcat.find("tech") > -1:
        self.inArticle = 1
        self.isMatch = 1

elif self.inArticle:
    if name == "header":
      self.title = attrs.get("title", "")
    if name == "body":
      self.inBody = 1

The last condition detects entry into a relevant body element. If true, the method characters now knows to buffer data when called:

def characters(self, characters):
   if self.inBody:     
     if len(self.body) < 80:
       self.body += characters
     if len(self.body) > 80:
       self.body = self.body[:78] + "..."
       self.inBody = 0

Finally, detect the closing body tag to tell the method characters to ignore subsequent character data:

def endElement(self, name):
   if name == "body":
     self.inBody = 0

Besides these three methods, initialize the class’s instance variables and add isMatch to indicate whether anything worth keeping was found. The next example shows the complete replacement for the earlier class of the same name.

 

Example: Improved ArticleHandler

from xml.sax.handler import ContentHandler

class ArticleHandler(ContentHandler):    
    """
    Ein Handler für Artikel in XML
    """
    inArticle = 0
    inBody = 0
    isMatch = 0
    title = ""
    body = ""
    
    def startElement(self, name, attrs):
        if name == "webArticle":
           subcat = attrs.get("subcategory", "")
           if subcat.find("tech") > -1:
             self.inArticle = 1
             self.isMatch = 1
        
        elif self.inArticle:
        if name == "header":
           self.title = attrs.get("title", "")
           if name == "body":
              self.inBody = 1
        
    def characters(self, characters):
        if self.inBody:
           if len(self.body) < 80:
             self.body += characters
           if len(self.body) > 80:
             self.body = self.body[:78] + "..."
             self.inBody = 0
          
    def endElement(self, name):
        if name == "body":
           self.inBody = 0

Using the extra information

With a handler collecting more information and identifying interesting articles, add code to art.py to report interesting articles and ignore the rest. Append this to art.py, originally shown in art.py:

if ch.isMatch:
    print "News!"
    print "Titel:", ch.title
    print "Text:", ch.body

With article.xml as input, you should see:

$> python art.py < article.xml
News!
Titel: NASA Builds Warp Drive
Text: Seattle, WA - Today an anonymous individual announced that NASA has com...

  

 

 

 

back to top