Decoding with C# XSD Code

Previous Menu Next

Decoding with C# Code Generated from XML Schemas

Let's first look at how you would decode an instance that conforms to the schema in the Purchase.xsd file that we've been using, which is reproduced here:

   <xsd:element name="purchase" type="PurchaseRecord"/>

   <xsd:complexType name="PurchaseRecord">
      <xsd:sequence>
         <xsd:element name="customer" type="CustomerType" maxOccurs="1"/>
         <xsd:element name="store" type="xsd:string" maxOccurs="1"/>
         <xsd:sequence maxOccurs="unbounded">
            <xsd:element name="item" type="xsd:string"/>
            <xsd:element name="price" type="xsd:float"/>
         </xsd:sequence>
      </xsd:sequence>
   </xsd:complexType>

   <xsd:complexType name="CustomerType">
      <xsd:simpleContent>
         <xsd:extension base="xsd:string">
            <xsd:attribute name="number" type="xsd:integer"/>
         </xsd:extensiion>
      </xsd:simpleContent>
   </xsd:complexType>
   

First, there are a couple of namespaces you will have to declare:

   using System.Xml;
   using System.IO;
   using <namespace>;

In the last "using" statement, <namespace> refers to the name of the namespace into which the Purchase_CC class is generated.

Your first step is to initialize a stream object that maps to your input file (assumed to be the string variable "filename" below). This is accomplished by using the FileStream class.

   FileStream fin = new FileStream(filename, FileMode.Open, FileAccess.Read);

Your next step is to create an XmlTextReader object against your input stream:

   XmlTextReader reader = null;
   try  {
      reader = new XmlTextReader(fin);

With that done, your next step is to create an instance of the control class object:

   Purchase_CC root = new Purchase_CC();

Now the decode operation can be done. This is accomplished by calling the generated decodeDocument() method on the Purchase_CC class:

   root.decodeDocument(reader);

So putting this all together, you'd have something like this:

   using System.Xml;
   using System.IO;
   using <namespace>;
   .
   .
   .
   FileStream fin = new FileStream(filename, FileMode.Open, FileAccess.Read);
   XmlTextReader reader = null;
   try  {
      reader = new XmlTextReader(fin);
      Purchase_CC root = new Purchase_CC();
      root.decodeDocument(reader);
      .
      .
      .
   }
   catch (Exception e) {
      .
      .
      .
   }

Previous Menu Next