C# XML Schema – Working with Multiple XML Schema Classes in C#

cschemaxml

I'm working with a data import process in C#, which takes a zip file filled with XML files and saves specific data points into a database. This is accomplished by loading the XML data into classes compiled from the schema. The import logic retrieves the data by digging down into the right classes and fields.

The XML schema is defined by a different company, and the schema changes every one to years when an updated version of their software is released. What my company would like to do is be able to import different versions of the schema so that we could support older files. There is also debate on whether this change is worth the effort.

My plan to accomplish this would be to determine which schema to use at the beginning of an import, and then use different interfacing classes to get the data from the XML and pass it back to the import classes, which would then save the values to the database. There are over 200 classes generated based on the schema, but we only need to access data in about half of them.

Are there other ways to approach supporting multiple XML schemas that may be easier?

Best Answer

You can put each set of classes of a schema into an assembly of its own. Then, load the right assembly dynamically at runtime after you identified the schema version. This technique is often used to create plug-ins (see here for an example).

To avoid the need of having all of your 200 classes implementing an interface, your import code can make use of the C# 4.0 dynamic keyword for accessing schema objects, regardless from which assembly they are loaded, as long as the method signature does not change between versions. See here for an example.

The drawback is that you will loose type-safety, you will have to decide if this is acceptable in your case.

Related Topic