5.11 Generate a Class from a Schema


Problem

You need to create one or more C# classes based on an XML schema. You can then create an XML document in the appropriate format using these objects and the XmlSerializer .

Solution

Use the xsd.exe command-line utility included with the .NET Framework. Specify the name of your schema file as a command-line argument, and add the /c parameter to indicate that you want to generate class code.

Discussion

Recipe 5.10 introduced the xsd.exe command-line utility, which can be used to generate schemas based on class definitions. The reverse operationgenerating C# source code based on an XML schema documentis also possible. This is primarily useful if you want to write a certain format of XML document, but you don't want to manually create the document by writing individual nodes with the XmlDocument or XmlTextWriter classes. Instead, by using xsd.exe, you can generate a set of full .NET objects. You can then serialize these objects to the required XML representation using the XmlSerializer , as described in recipe 5.9.

To generate source code from a schema, you simply need to supply the filename of the schema document and add the /c parameter to indicate that you want to generate the required classes. For example, consider the schema shown in recipe 5.8. You can generate C# code for this schema with the following command-line:

 xsd ProductCatalog.xsd /c 

This will generate one file (ProductCatalog.cs) with two classes: product and productCalalog . These classes are similar to the ones created in recipe 5.9, except for the fact that the class member names match the XML document exactly.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net