If you're using XmlSerializer
, XmlAttributeOverrides
is probably what you need.
Update:
I've been investigating the possibilities of customizing the date format, and, as far as I can see, no pretty solutions exist.
One option, as has been mentioned by others, is to implement IXmlSerializable
. This has the drawback that you're completely responsible for (de-)serializing the entire object(-graph).
A second option, with also quite an extensive list of drawbacks, is to subclass the base class (you mentioned it as an alternative in your post). With quite some plumbing, conversions from and to the original object, and the use of XmlAttributeOverrides
you could build something like this:
public class Test
{
public int Prop { get; set; }
public DateTime TheDate { get; set; }
}
public class SubTest : Test
{
private string _customizedDate;
public string CustomizedDate
{
get { return TheDate.ToString("yyyyMMdd"); }
set
{
_customizedDate = value;
TheDate = DateTime.ParseExact(_customizedDate, "yyyyMMdd", null);
}
}
public Test Convert()
{
return new Test() { Prop = this.Prop };
}
}
// Serialize
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributes = new XmlAttributes();
attributes.XmlIgnore = true;
overrides.Add(typeof(Test), "TheDate", attributes);
XmlSerializer xs = new XmlSerializer(typeof(SubTest), overrides);
SubTest t = new SubTest() { Prop = 10, TheDate = DateTime.Now, CustomizedDate="20120221" };
xs.Serialize(fs, t);
// Deserialize
XmlSerializer xs = new XmlSerializer(typeof(SubTest));
SubTest t = (SubTest)xs.Deserialize(fs);
Test test = t.Convert();
It ain't pretty, but it will work.
Note that you're actually (de-)serializing SubTest objects in this case. If the exact type is important, this is not going to be an option too.