Include key value pairs in XSD schema generated from C# class



I have a class written in C#. This class is now going to be used in an API where an XML document is posted to the API. I need to generate a schema (XSD) to dictate the rules of the XML files that will be posted.


What I am really struggling with though is a way of annotating (?) my class so that the schema lists possible values for certain properties within the class. I'll be using "xsd.exe" to generate the XSD.


The possible values need to be listed as key value pairs. e.g. I have a property called Gender where the possible values are "M" and "F". These are obvious in that they mean "Male" and "Female".


What isn't so obvious is my property "StType" (street type). e.g. some valid values are "AC", "AL", "AN", "AP", "AR", and "AV". These correspond to "Access", "Alley", "Anchorage", "Approach", "Arcade", and "Avenue".


So what I want is a way to mark my class properties with key value pairs that will be translated to my schema. "XmlElementRestrictionsList" is made up below but I'm wanting something that does this sort of thing.



[XmlElementRestrictionsList{"M":"Male", "F":"Female"}]
public string Gender { get; set; }


This would in turn generate a schema something like



<xsd:element name="Gender" minOccurs="1">
<xsd:restriction type="string">
<xs:enumeration value="Male, M" />
<xs:enumeration value="Female, F" />
</xsd:restriction>
</xsd:element>


I don't know if that's actually how the schema writes it out but hopefully it's enough to get across what I am trying to achieve.


I've Googled a lot about string Enums but 1. I'm not entirely sure how to do this in my class and 2. more importantly, I have seen nothing that suggests key value pairs are an option. I DO NOT want my values corresponding to an Enum number ("M" = 1, "F" = 2).


And what is probably a really simple extra, how do I mark in the schema that something is required (in my class, ready for the schema generator)? Such as Gender, FirstName, and LastName (all strings in my class) must be included in the posted XML whereas Title and Phone can be missing entirely. I'm assuming that's what the "minOccurs" means. Although what I mean is required not minimum number of possibly multiple times.



[XmlElementRequired]
public string Gender { get; set; }

No comments:

Post a Comment