CaptainNemo
CaptainNemo

Reputation: 1552

Generating XSD from a Class in C#

I am making a program which saves the configuration to XML files.

I currently use XMLserializer to generate XML from classes and vica versa.

I want to be able to generate also an XSD file from the class to be able to validate future XML files, including ones that were not generated automatically.

This ability should include the option to specify properties for the elements such as minValue, maxLength and default value (maybe by using annotations).

The only tool I've read about so far is XSD.exe which I do not know how to use programmatically (from the C# code) and if it is even a good way to do so.

Upvotes: 0

Views: 1508

Answers (2)

Amin Uddin
Amin Uddin

Reputation: 1006

 Go to your command prompt. After that go to the following path
 1.C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64>
 2. After that write 
 xsd.exe
 3. After that paste you .dll file path.
 4. run command
 5.Output: Go to the following location:(** Command prompt indicate you about such link) and you will see your desire xsd file schema
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0
Tools\x64\

Example: in CMD.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64>xsd.
exe "E:\TFS Projects\Project\Admin\BO\bin\Debug\BO.dll"
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0
Tools\x64\schema0.xsd'.

Upvotes: 0

atkretsch
atkretsch

Reputation: 2397

There are other tools for generating C# from XSD (such as XSD2Code), but I don't know offhand if they have a programmatic API.

You could always launch an XSD.exe (or any other tool) process from within your C# application using Process.Start(). A quick-and-dirty example:

var proc = Process.Start(new ProcessStartInfo
    {
        FileName = "xsd.exe",
        Arguments = "/c /namespace:Your.NameSpace yourXsdFile.xsd /o:\"C:\\yourOutputDir\\\"",
        WindowStyle = ProcessWindowStyle.Hidden,
        UseShellExecute = false
    });
proc.WaitForExit();
var exitCode = proc.ExitCode;
if (exitCode == 0)
{
    // post-processing
}
else
{
    // handle errors
}

Obviously there are some details to fill in, and you'd need XSD.exe to be in your PATH (or alternatively, specify the full path to it in code), etc., but the basic idea should work.

Upvotes: 1

Related Questions