13.4.1 Example
Keywords: lib

##
13.4.1 Example

The following program defines three handlers that just print out their arguments.

      import xml.parsers.expat

      # 3 handler functions
      def start_element(name, attrs):
          print 'Start element:', name, attrs
      def end_element(name):
          print 'End element:', name
      def char_data(data):
          print 'Character data:', repr(data)

      p = xml.parsers.expat.ParserCreate()

      p.StartElementHandler = start_element
      p.EndElementHandler = end_element
      p.CharacterDataHandler = char_data

      p.Parse("""<?xml version="1.0"?>
      <parent id="top"><child1 name="paul">Text goes here</child1>
      <child2 name="fred">More text</child2>
      </parent>""")

The output from this program is:

      Start element: parent {'id': 'top'}
      Start element: child1 {'name': 'paul'}
      Character data: 'Text goes here'
      End element: child1
      Character data: '\012'
      Start element: child2 {'name': 'fred'}
      Character data: 'More text'
      End element: child2
      Character data: '\012'
      End element: parent