Steve Chambers Steve Chambers - 1 year ago 103
C# Question

How to read serialized data into a set of entity classes?

I've been assigned a task to import reference data from a database into a set of entity classes. Here's an example of one of the simpler entity classes:

public class CountryList
public CountryList()
this.Countries = new List<Country>();

public IList<Country> Countries { get; private set; }

Populating the XML files isn't my responsibility. But providing a schema (XSD file) in order to specify the required format is.

So far I've tried annotating the required classes/members with
and using
to generate a set of XSD files using this command:

svcutil /t:metadata /dconly MyProject.dll

This generates a lot of stuff in 10 separate XSD files. I couldn't find a way of specifying only the entities I'm interested in and slimming it all down. (It is only some reference data that needs to be imported and there are plenty of entity classes that don't need to be in the XSD).

On an alternative tack, I found this article on how to deserialize from an XML file. Looks pretty simple on the face of it but I'm wondering how the XSD file for the
class in this example would be generated?

Answer Source

It turned out to be a lot cleaner to generate an XSD using code (rather than using either xsd.exe or svcutil.exe). Here are the steps I followed:

  1. Create a new Console Application like this but using a StreamWriter to output to a file instead of the console. The resulting XSD has just the entities I need and no more. The [DataContract] / [DataMember] attributes cause XSD constructs to have the same names as in the code.

  2. Use Eclipse to generate sample XML from the XSD like this.

  3. Use code like this to deserialize the XML file into the required entities.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download