#!/usr/bin/python#-*-coding:utf-8-*-ImportXml.saxclassMoviehandler (xml.sax.ContentHandler):def __init__(self): Self.stack= [] #element Start Event handling defstartelement (self, Tag, attributes):ifLen (self.stack)! =0:Print "\ n","*"*4*Len (self.stack), attr="" #Property Value ifAttributes.getlength () >0: forAttrnameinchattributes.getnames (): attr=" "+ attr + attrname +"="+Attributes.getvalue (attrname)Print "<"+tag+attr+">", Self.stack.append ("Start") #element End Event handling defendElement (self, tag):ifSelf.stack[len (Self.stack)-1] = ="content" andSelf.stack[len (Self.stack)-2] = ="Start": delSelf.stack[len (Self.stack)-1] delSelf.stack[len (Self.stack)-2] elifSelf.stack[len (Self.stack)-1] = ="Start": delSelf.stack[len (Self.stack)-1] Print "\ n","*"*4*Len (self.stack),Print "</"+tag+">", #Content Event Handling defcharacters (self, content):ifContent.strip ()! ="': Self.stack.append ("content") Printcontent,if(__name__=="__main__"): #Create a XMLReaderParser =Xml.sax.make_parser ()#Turn off Namepsacesparser.setfeature (xml.sax.handler.feature_namespaces, 0)#rewrite ContexthandlerHandler =Moviehandler () Parser.setcontenthandler (Handler) parser.parse ("Movie.xml")
XML document:
<CollectionShelf= "New Arrivals"><movietitle= "Enemy Behind"> <type>War, Thriller</type> <format>Dvd</format> < Year>2003</ Year> <rating>Pg</rating> <stars>10</stars> <Description>Talk about a Us-japan war</Description></movie><movietitle= "Transformers"> <type>Anime, science fiction</type> <format>Dvd</format> < Year>1989</ Year> <rating>R</rating> <stars>8</stars> <Description>A schientific Fiction</Description></movie> <movietitle= "Trigun"> <type>Anime, Action</type> <format>Dvd</format> <episodes>4</episodes> <rating>Pg</rating> <stars>10</stars> <Description>Vash the stampede!</Description></movie><movietitle= "Ishtar"> <type>Comedy</type> <format>Vhs</format> <rating>Pg</rating> <stars>2</stars> <Description>Viewable boredom</Description></movie></Collection>
Parse Output:
See also: http://www.cnblogs.com/hongfei/p/python-xml-sax.html
[Python Learning] Sax