I'm working on some classes in c#. They need to be serialized to XML to match an existing schema, but I want to build the validation in the code. e.g. something like the below;
public class Address {
public AddressLineType AddressLine1 {get;set;}
public AddressLineType AddressLine2 {get;set;}
public ShortAddressLineType AddressTown {get;set;}
public ShortAddressLineType AddressCounty {get;set;}
public PostCodeType PostCode {get;set;}
}
public class SimpleString {
public string Value {get;set;}
public override string ToString() {
return Value;
}
}
public class AddressLineType : SimpleString {
static readonly int maxLength = 60;
public static explicit operator AddressLineType(string v) {
if(!(v.Length < maxLength)) throw new Exception("String is to long!");
AddressLineType s = new AddressLineType();
s.Value = v;
return s;
}
}
public class ShortAddressLineType : SimpleString {
static readonly int maxLength = 30;
public static explicit operator ShortAddressLineType(string v) {
if(!(v.Length < maxLength)) throw new Exception("String is to long!");
ShortAddressLineType s = new ShortAddressLineType();
s.Value = v;
return s;
}
}
public class PostCodeType : SimpleString {
public static explicit operator PostCodeType(string v) {
Regex regex = new Regex(""); //PostCode pattern..
if(!(regex.IsMatch(v))) throw new Exception("Regex Validation Failed.");
PostCodeType s = new PostCodeType();
s.Value = v;
return s;
}
}
However, when this is serialized the result is;
<CurrentAddress>
<AddressLine1>
<Value>3 The Street</Value>
</AddressLine1>
<AddressLine2>
<Value>Foo Town</Value>
</AddressLine2>
</CurrentAddress>
Is it possible to collapse the special classes so that the result is this instead, but still be able to do validation? e.g. I need to specify that the AddressLineType serialises to it's Value only.
<CurrentAddress>
<AddressLine1>3 The Street</AddressLine1>
<AddressLine2>Foo Town</AddressLine2>
</CurrentAddress>
This code prints the result;
Address address = new Address();
address.AddressLine1 = (AddressLineType) "3 The Street";
address.AddressLine2 = (AddressLineType) "Foo Town";
XmlSerializer serializer = new XmlSerializer(typeof(Address));
serializer.Serialize(Console.Out, address);