Home > Software design >  Generate C# 9 classes from an XML schema file (xsd), including modern features (nullables mostly)
Generate C# 9 classes from an XML schema file (xsd), including modern features (nullables mostly)

Time:01-08

I have to implement support for ISO20022 file format in our application and the "xsd.exe" tool provided with Visual Studio 2022 is frustratingly inadequate.

The most frustrating point is the lake of proper support for nullable types in the generated code: when a XML element is marked as "optional", the generated code should properly generate a nullable member in the target class. Instead, it generates a mess of two fields (MemberName and MemberNameSpecified}.

This makes the code working with the result way less readable than it should and more error prone.

Another sore point is the missing support for related schemas: various versions of the ISO2022 XML schema files exists and financial entities typically do not support them all. Since the xsd.exe tool does not (to my knowledge) allow mappinh of multiple XSD and namespaces into a single C# namespace, identical elements in the spefifications generates identical objects but in different C# namespace. This force us to cut and paste identical code for identical objects that are in different namespaces.

Is there a way to get XSD.exe to generate a "modern" class from an XML shema?

Is there another tool that could fit the bill (paid tools are ok if they get the job done).

CodePudding user response:

There are 2 really good open source and free options for C#/.NET (including Core Framework):

  • https://github.com/mamift/LinqToXsdCore

    Back in 2008, Microsoft did work on improving XSd.exe, and they shipped a successor tool called LinqToXsd, which improves upon XSD.exe in many ways. It has been ported over to .NET Core and does support multiple namespaces (importing including), and adding #nullable enable annotations to the generated code. This tool produces .NET Standard 2 code that is very different from XSD.exe, and tries to model the schema more closely than XSD.exe. See some sample code here.

  • https://github.com/mganss/XmlSchemaClassGenerator

    This project is newer, and has better support for #nullables through the AllowNullAttribute and MaybeNullAttribute instead of just the #nullable pragma. This project can also generate interfaces from element and attribute groups, which is nifty when you need it, which neither XSD.exe nor LinqToXsdCore supports. This tool also generates code that looks closer to what XSD.exe gives you.

You might want to fiddle with both of them before making a decision. But I recommend using XmlSchemaClassGenerator, unless you have legacy code based on the old .NET Framework version of LinqToXsd, then LinqToXsdCore is more compatible as it is a straight-forward port.

  • Related