I have a DateTime and a subclass that I want formatted specifically on XML serialization. Normally, without specifying anything, serialization of a DateTime would just follow the current culture, but I want DateTime formatted in a certain way (even if not deserializable), ditto the subclass.
So, given these classes:
public class MyClass
{
public DateTime MyDateTime { get; set; }
public MySubClass TheSubClas开发者_JAVA技巧s { get; set; }
}
public class MySubClass
{
public int ID { get; set; }
public string Name { get; set; }
}
How do I specify serialization methods that would output:
<MyClass>
<MyDateTime>2011-9-13T10:30:00Z</MyDateTime>
<MySubClass>ID-Name</MySubClass>
</MyClass>
Are you utilizing XmlSerializer? If so, you do not need to include the [Serializable] attributes, they are ignored by XmlSerializer. You can customize the serialization by implementing the IXmlSerializable interface on your type.
http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx
This is off the top of my head ...I haven't nested a type in Xml serialization as you have - but this should be close.
[XmlRoot]
public class MyClass
{
[XmlElement]
public DateTime MyDateTime { get; set; }
[XmlElement]
public MySubClass TheSubClass { get; set; }
}
[XmlRoot]
public class MySubClass
{
[XmlElement]
public int ID { get; set; }
[XmlIgnore] // since you didn't include in XML snippet
public string Name { get; set; }
}
If you are performing simple Xml serialization: check MSDN XmlSerializer.
Update
I missed I want DateTime formatted in a certain way ...what I've done is the following rather than implementing IXmlSerializable
:
[XmlRoot]
public class MyClass
{
[XmlElement]
public string MyDateTime { get; set; }
[XmlIgnore]
public DateTime DT
{
get { /* return DateTime from MyDateTime */ }
set { MyDateTime = value.ToString( /* use formatting */); } // ex. ToString("yyyy, MMMM dd : hh:mm")
}
[XmlElement]
public MySubClass TheSubClass { get; set; }
}
精彩评论