from xml.sax import parse, SAXParseException, ContentHandler
class TagInfoHandler( ContentHandler ):
def __init__( self, tagName ):
ContentHandler.__init__( self )
self.tagName = tagName
self.depth = 0
def startElement( self, name, attributes ):
if name == self.tagName:
print "\n%s<%s> started" % ( " " * self.depth, name )
self.depth += 3
print "%sAttributes:" % ( " " * self.depth )
for attribute in attributes.getNames():
print "%s%s = %s" % ( " " * self.depth, attribute,
attributes.getValue( attribute ) )
def endElement( self, name ):
if name == self.tagName:
self.depth -= 3
print "%s</%s> ended\n" % ( " " * self.depth, name )
file = "text.xml"
tagName = "tagName"
try:
parse( file, TagInfoHandler( tagName ) )
except IOError, message:
print "Error reading file:", message
except SAXParseException, message:
print "Error parsing file:", message