python-parsing XML files using Xml.sax

Source: Internet
Author: User

What is sax?

Sax is an event-driven API.

Parsing an XML document with sax involves two parts: the parser and the event handler.

The parser is responsible for reading the XML document and sending events to the event handler, such as the element starting with the element end event;

The event handler is responsible for the event, processing the passed XML data.

Sax is suitable for handling the following issues:

    • 1, to deal with large-scale documents;
    • 2, only need some content of the file, or just get the specific information from the file;
    • 3, want to build their own object model when.

Using sax in Python to process XML first introduces the parse function in Xml.sax and the ContentHandler in Xml.sax.handler.

Movies.xml: The XML file that needs parsing, as in the previous blog using DOM parsing
<collection shelf="New Arrivals"><movie title="Enemy Behind"> <type>war, thriller</type> <format>DVD</format> <year>2003</year> <rat Ing>pg</rating> <stars>10</stars> <description>talk about a us-japan war</description& Gt;</movie><movie title="Transformers"> <type>anime, Science fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>a schientific fiction</descripti On></movie><movie title="Trigun"> <type>anime, action</type> <format>DVD</format> <episodes>4</episodes> &L T;rating>pg</rating> <stars>10</stars> <description>vash the Stampede!</description ></movie><movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars&gt ;2</stars> <description>viewable boredom</description></movie></collection>

xmltest.py: The parsing code is as follows
#-*-coding:utf-8-*-" "Created on September 10, 2015 @author:xiaowenhui" "ImportXml.sax#the second method, sax parsingClass Moviehandler (Xml.sax.ContentHandler): #继承于xml. Sax.contenthandler class Def __init__ (self): self. CurrentData = "Self.type =" "Self.format =" "Self.year =" "Self.episodes =" "Self . rating = "" Self.stars = "" Self.description = "" Self.title = "" # element Start Event processing def startelement ( Self, Tag, attributes): self.             CurrentData = Tag if tag = = "movie": Print "*****movie*****" Self.title = attributes["title"] Print "Title:", Self.title # Content event Processing def characters (self, content): if self. CurrentData = = "Type": Self.type = content elif self. CurrentData = = "format": Self.format = content elif self. CurrentData = = ' Year ': self.year = content elif self. CurrentData = = "Episodes": Self.episodes = content elif self. CurrentData = = "rating": self.rating = content elif self. CurrentdATA = = "Stars": self.stars = content elif self. CurrentData = = "description": self.description = content # element End Event Handling def endElement (self, tag) : If self. CurrentData = = "type": print "type:", Self.type elif self. CurrentData = = "format": print "format:", Self.format elif self. CurrentData = = "Year": print ' Year: ', Self.year elif self. CurrentData = = "Episodes": Print "Episodes:", Self.episodes elif self. CurrentData = = "rating": print "rating:", self.rating elif self. CurrentData = = "Stars": print "stars:", Self.stars elif self. CurrentData = = "description": Print "description:", Self.description # Create a Xmlread Erparser = Xml.sax.make_parser () # Turn off Namepsacesparser.setfeature (xml.sax.handler.feature_namespaces, 0) # rewrite Contexthandlerhandler = Moviehandler () parser.setcontenthandler (Handler) pArser.parse ("Movies.xml") 

The output results are as follows:

Doubt: I do not know why the output of a description, may be sax parsing when the wrong writing, and now did not find the reason, I put

Elif self. CurrentData = = "description": Print "description:", self.description

Change into
Elif self. CurrentData = = "description": Print  self.description
There is no output "description", only the output of self.description this parameter

movie*****title:enemy Behindtype:war, Thrillerformat:dvdyear:2003Rating:pgstars:10Description:talk about a US-Japan wardescription:movie*****Title:TransformersType:Anime, Science fictionformat:dvdyear:1989Rating:rstars:8description:a schientific fictiondescription:movie*****Title:TrigunType:Anime, Actionformat:dvdepisodes:4Rating:pgstars:10Description:vash the stampede!description:movie*****Title:IshtarType:ComedyFormat:VHSRating:PGStars:2description:viewable boredomdescription:description:

python-parsing XML files using Xml.sax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.