by JasonRShaver
30. July 2008 16:44
Not sure if you knew this, but there are two was to “include” a type for xml serialization:
This one is more common:
(Add it to the Serializer)
XmlSerializer MyXmlSerializer = new XmlSerializer(typeof(CopyMeScript), new Type[] {typeof(CommandItem)} );
But this one is in most cases better:
(Add include attributes to the class)
[Serializable]
[XmlInclude(typeof(CommandItem))]
[XmlRoot(ElementName="CopyMeScript", IsNullable=false)]
public partial class CopyMeScript
{
Just an FYI for you. Doing this has helped my manageability of code so much because now you don’t need to remember what types you need to include every time you write a new serialization function. You can also add includes to the base class of a class and they carry over allowing you to do valid object orientated generic serialization classes such as this method that can serialize anything:
public string ToXml(T objectToSerialize)
{
if (((object)objectToSerialize).GetType().IsSerializable == false)
throw new ArgumentException("Given object is not serializable");
XmlSerializer MyXmlSerializer = new XmlSerializer(typeof(T));
MemoryStream MyStream = new MemoryStream();
MyXmlSerializer.Serialize(MyStream, objectToSerialize);
MyStream.Position = 0;
StreamReader MyReader = new StreamReader(MyStream);
string Output = MyReader.ReadToEnd();
MyStream.Close();
return Output;
}
f3340dd4-8c70-4544-9e5b-c7cc694c1289|0|.0
Tags:
Blog