49

What is the best way to generate C# classes from multiple XSD schema files?

Some XSD schema files may have dependency to the other, I am trying to avoid duplicated C# classes being generated.

2 Answers 2

64

Use the XSD.EXE program, but pass all of the schemas to the program on the same command line.

For example:

> xsd /c qbxmltypes130.xsd QBUqbxmlops130.xsd QBUqbxmlso130.xsd QBUqbxml130.xsd

Will emit a class named:

qbxmltypes130_QBUqbxmlops130_QBUqbxmlso130_QBUqbxml130.cs

In this case these are Quickbooks Desktop SDK xsd files, and the final file has types it depends on in the first 3 files. It won't emit on its own, but with its dependencies it works as desired.

Note that there is a /parameters:<file> switch that allows you to specify a file of command line parameters. I remember using it in one project for a similar reason.

XSD.EXE doc has the parameter format.

5
  • 4
    Just adding an example "xsd.exe /classes /n:{your_namespace} {file1}.xsd {file2}.xsd {file3}.xsd /out:{your output folder}" Jul 3, 2014 at 15:11
  • No need to use Altova XML Spy for generating C# classes from XSDs with multiple references from now on.
    – setzamora
    Jun 24, 2015 at 4:06
  • 1
    A final addition to the excellent example @vivekp gave: The last file named in the sequence seems to be the one used for generating the class file name. So his example would produce the class file {your output folder}\{file3}.cs Dec 20, 2015 at 4:30
  • 1
    Gives an error and doesn't generate classes if you have circular group references. Dec 12, 2017 at 12:52
  • 1
    Thanks, for the answer. Mar 19, 2018 at 5:28
35

I for one found the examples in the MSDN doc a bit lacking. Here's an example parameters file for the issue codemeit described:

<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
<generateClasses language='CS' namespace='Namespace.subnamespace'>
    <schema>FirstSchema.xsd</schema>
    <schema>AnotherSchema.xsd</schema>
    <schema>LastSchema.xsd</schema>
</generateClasses>
</xsd>
3
  • 1
    Thanks, @anony_mouse -- I was looking for a good example of that syntax!
    – ewall
    Oct 4, 2010 at 18:37
  • 15
    if you get the error "specified path or file name too long" try placing a ".\" infront of the last file and it resolves the problem, note that the output file will then be named by the last file..
    – Peter
    Nov 19, 2013 at 7:21
  • 1
    Might be worth mentioning this file has to have the .xml extension and not .xsd. Battled for a bit there, and my includes are over 50. But managed to get it working, it only took 2 seconds to generate Aug 17, 2021 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.