Parse XML instance _python using sax in Python

Source: Internet
Author: User

Sax is an event-based-driven API. Using SAX to parse XML documents involves two parts: parsers and event handlers. The parser is responsible for reading the XML document and sending events to the event handler, such as when the element starts with the element end event, and the event handler is responsible for handling the passed XML data by responding to the event.

Instance:

Copy Code code as follows:

Import sys, string from xml.sax import handler, Make_parser

Class Testhandler (handler. ContentHandler):
def __init__ (self):
Pass

def startdocument (self):
Print "Document Start ..."

def enddocument (self):
Print "Document end ..."

def startelement (self, Name, attrs):
print ' start tag: ', name

def endelement (self, name):
print ' end tag: ', name

def characters (self, chrs):
Print chrs


def test ():
Handler = Testhandler ()
Parser = Make_parser ()
Parser.setcontenthandler (Handler)
f = open (Sys.argv[1], ' R ')
Parser.parse (f)
F.close ()

if __name__ = = ' __main__ ':
Test ()

Another way to read and write files in addition to the DOM.

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.