Sept. 24, 2010, 10:46 a.m.
posted by angryuser
Creating Classes from SchemasThe preceding section demonstrated how to use various attributes to control the XML to be serialized. Often, you don't need to create these classes yourself, nor add the correct mixture of attributes, but instead can rely on the Web service infrastructure to create the classes for you at design time. If you have a schema document, then you can give it to a tool called xsd.exe, which can create all of the classes for you. The classes it creates will be similar to structs, in that they won't contain any methods but will only have fields. Because properties will not be generated for you, you will have to edit the class by hand in order to change them.
For example, let's imagine we have a fairly simple schema:
<?xml version="1.0" encoding="utf-8" ?>
<s:schema
targetNamespace="http://tempuri.org/XMLSchema.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/XMLSchema.xsd"
xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
xmlns:s="http://www.w3.org/2001/XMLSchema">
<s:element name="library" type="mstns:Library" />
<s:complexType name="Library">
<s:sequence>
<s:element
minOccurs="0"
maxOccurs="1"
name="books"
type="mstns:ArrayOfBook" />
<s:element
minOccurs="0"
maxOccurs="1"
name="Name"
type="s:string" />
<s:element
minOccurs="0"
maxOccurs="1"
name="Location"
type="s:string" />
</s:sequence>
</s:complexType>
<s:complexType name="ArrayOfBook">
<s:sequence>
<s:element
minOccurs="0"
maxOccurs="unbounded"
name="Book"
nillable="true"
type="mstns:Book" />
</s:sequence>
</s:complexType>
<s:complexType name="Book">
<s:sequence>
<s:element
minOccurs="0"
maxOccurs="1"
name="Name"
type="s:string" />
<s:element
minOccurs="0"
maxOccurs="1"
name="ISBN"
type="s:string" />
</s:sequence>
</s:complexType>
</s:schema>
By calling xsd.exe, we can create a set of classes based on this schema, as shown in Listing 5.7. Xsd.exe /c OurSchema.xsd Classes Created from a Simple Schema Using xsd.exe
using System.Xml.Serialization;
[XmlTypeAttribute(Namespace="http://tempuri.org/XMLSchema.xsd")]
[XmlRootAttribute("library",
Namespace="http://tempuri.org/XMLSchema.xsd",
IsNullable=false)]
public class Library {
public Book[] books;
public string Name;
public string Location;
}
[XmlTypeAttribute(Namespace="http://tempuri.org/XMLSchema.xsd")]
public class Book {
public string Name;
public string ISBN;
}
Notice that the default is to create these in C#. You can set the language to one of several languages, including VB.NET. In addition, there is a setting to put these classes in a CLR namespace rather than in the default namespace. When you use wsdl.exe, you can also expect classes to be created based on the schema section of the WSDL. These classes will be nearly identical to the classes created from xsd.exe. You also can expect Visual Studio .NET's Add Web Reference dialog box to behave similarly to wsdl.exe (as explained in Chapter 4, Creating Web Service Clients). |
- Comment