Generated Decode Methods when Using the SAX parser

As noted above, -sax can be used to generate SAX-based parsing code. This section discusses the code that is generated in that case.

As a SAX parser parses XML, it invokes callbacks on a content handler interface to notify any interested parties of the data it has parsed. ASN1C generates an implementation of the content handler interface as an inner class of each class generated for an ASN.1 production. This content handler populates the fields of the data class as the XML is parsed. The generated content handler includes the following methods:

   StartElement
 
    Characters
 
    EndElement

The procedure to invoke the generated decode method is as follows:

  1. Instantiate an XmlSaxParser object.

  2. Instantiate a generated C# <ProdName> object to hold the decoded message data.

  3. Invoke the <ProdName> object decode method passing the reader created in step 1 and the URI of the XML document to be parsed. This method initiates and invokes the XML parser’s parse method to parse the document. This, in turn, invokes the generated SAX handler methods.

  4. Methods within the <ProdName> object can now be used to access the decoded data. The member variables that were declared to be public can be accessed directly.

  5. Error handling is accomplished using a try-catch block to catch SAX exceptions.

A program fragment that could be used to decode an employee record is as follows:

   public class Reader {
      public static void main (string args[]) {
         string filename = "employee.xml";
 
         try {
            // Create an XML reader object
 
            XmlSaxParser reader = XmlSaxParser.NewInstance();
 
            // Read and decode the message
 
            PersonnelRecord personnelRecord = new PersonnelRecord ();
            personnelRecord.Decode (reader, filename);
            if (trace) {
               System.Console.Out.WriteLine ("Decode was successful");
               personnelRecord.Print ("personnelRecord");
            }
         }
         catch (Exception e) {
            System.Console.Out.WriteLine (e.Message);
            Asn1Util.WriteStackTrace(e, Console.Error);
            return;
         }
      }
    }