5.10 Create a Schema for a .NET Class


Problem

You need to create an XML schema based on one or more C# classes. This will allow you to validate XML documents before deserializing them with the XmlSerializer .

Solution

Use the XML Schema Definition Tool (xsd.exe) command-line utility included with the .NET Framework. Specify the name of your assembly as a command- line argument, and add the /t:[TypeName] parameter to indicate the types you want to convert.

Discussion

Recipe 5.9 demonstrated how to use the XmlSerializer to serialize .NET objects to XML, and deserialize XML into .NET objects. But if you want to use the XML as a way to interact with other applications, business process, or non-Framework applications, you'll need an easy way to validate the XML before you attempt to deserialize it. You'll also need to define an XML schema document that defines the structure and data types used in your XML format, so that other applications can work with it. One quick solution is to generate an XML schema using the xsd.exe command-line utility.

The xsd.exe utility is included with the .NET Framework. If you've installed Microsoft Visual Studio .NET, you'll find it in a directory like C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin. The xsd.exe utility can generate schema documents from compiled assemblies. You simply need to supply the filename and indicate the class that represents the XML document with the /t:[TypeName] parameter.

For example, consider the ProductCatalog and Product classes shown in recipe 5.9. You could create the XML schema for a product catalog with the following command line:

 xsd Recipe5-09.exe /t:ProductCatalog 

You need to specify only the ProductCatalog class on the command line because this class represents the actual XML document. The generated schema in this example will represent a complete product catalog, with contained product items. It will be given the default filename schema0.xsd. You can now use the XmlValidatingReader shown in recipe 5.8 to test whether the XML document can be successfully validated with the schema.




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