Encoding with C# Code Generated from XML Schemas
Encoding is similar to decoding. Let's look at how you would do the encoding to create the instance that we looked at earlier:
You first have to declare the System.IO namespace:
Then you need to declare the namespace for the generated classes that you'll be using:
In the above "using" statements, <namespace> refers to the namespace into which the classes were generated.
And last, you need to declare the namespace for the XBXmlEncoder class from the XBinder C# runtime:
Then you need to create an instance of the generated Purchase_CC control class:
Your next step is to populate the generated structures with the information you want to appear in the instance. You start by creating an instance of the PurchaseRecord class, which is the class for the global element in the .xsd file:
Be careful not to get this confused with the control class. The control class is a class that encapsulates even this global element and gives you the ability to decode and encode the entire message.
At this point you can populate the objects with the data that needs to appear in the instance. Since the first item in the instance is a customer, you can set up the customer information first:
This sets up a customer object that's referenced by the PurchaseRecord object.
Next you can define the value for the store element within the purchase record:
Next is the possibly repeating sequence of item and price elements. To define one instance of this possibly repeating data, you need to create a PurchaseRecord_3 object:
This object, then, can be populated with an item description and a price:
Note the need to cast the literal 750.00 to (float). In C# decimal literals are double by default.
The next step is to put the populated item and price structure into the linked list that's generated to handle the sequence that might repeat:
The last step before encoding is to set the PurchaseRecord instance into the Purchase_CC control class:
And now the actual encoding can be done:
The encodeDocument() method is a generated method to handle the encoding of a PurchaseRecord instance that's wrapped in a Purchase_CC control class instance.
The steps above write the encoded instance to a file. If desired, you could create the XBXmlEncoder object using a MemoryStream instead of a FileStream. This process would give you an in-memory copy of the encoded message.
So putting all of this together, you have something like this:
To compile this code, you need to specify the XBinder C# runtime assembly as a dependency. This assembly is named xbrt.dll and is included in your XBinder distribution in the "csharp" subdirectory underneath your main XBinder install directory. For example, if you installed XBinder into the folder c:\xbv260 on a Windows system, then the xbrt.dll file would be in c:\xbv260\csharp.