How do I serialize a 'Type'?
I want to serialize to XML an object that has a property that is a type of an object. The idea is that when it is deserialized I can create an object of that type.
public class NewObject
{
}
[XmlRoot]
public class XmlData
{
private Type t;
public Type T
{
get { return t; }
set { t = value; }
}
}
static void Main(string[] args)
{
XmlData data = new XmlData();
data.T = typeof(NewObject);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlData));
try
{
using (FileStream fs = new FileStream("test.xml", FileMode.Create))
{
serializer.Serialize(fs, data);
}
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
I get this exception: "The type ConsoleApplication1.NewObject was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
Where do I put the [XmlInclude]? Is this even possible?
As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.
Basic and custom serialization Binary and XML serialization can be performed in two ways, basic and custom.
Type
class cannot be serialized because System.RuntimeType
is not accessible to our code, it is an internal CLR type. You may work around this by using the type's name instead, like this:
public class c
{
[XmlIgnore]
private Type t;
[XmlIgnore]
public Type T {
get { return t; }
set {
t = value;
tName = value.AssemblyQualifiedName;
}
}
public string tName{
get { return t.AssemblyQualifiedName; }
set { t = Type.GetType(value);}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With