Thursday, July 12, 2007

How to generate an XSD file from an existing class

Since one of my co-workers ask me how to generate an XSD file from an existing class today, I decided to post an example of how to do it.

First, I need a class to convert, so I will generate an XSD file from this class, which resides inside of an assembly called MyClassLibrary.dll:

using System.Xml.Serialization;

namespace MyNameSpace
{
[XmlRoot("Customer", Namespace ="http://www.yates.com/BusinessObjects/2007/07")]
public class Customer
{
private string _firstName;
private string _middleName;
private string _lastName;

public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}

public string MiddleName
{
get { return _middleName; }
set { _middleName = value; }
}

[XmlIgnore]
public string Name
{
get
{
if (string.IsNullOrEmpty(MiddleName) == false)
return string.Format("{0} {1} {2}", FirstName, MiddleName, LastName);
else return string.Format("{0} {1}", FirstName, LastName);
}
}
}
}
Next, a command prompt window is opened in the same directory as MyClassLibrary.dll.

Afterwards, the following command is used to generate the XSD:
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe" MyClassLibrary.dll /t:Customer



Finally, an XSD file called schema0.xsd is generated in the same directory as the assembly. It looks like this:

3 comments:

andy said...

Do you know how to use XSD.exe to generate XSD Schema from classes that are defined in two or more assemblies? Thanks

Dave said...

Andy,

I'm not a expert at using the tool. I can only suggest that you check here on the msdn site:
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

Anonymous said...

Dave, thanks for this. Exactly what I was looking for. Concise and to the point! A rare thing indeed.