Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize XML without knowing the type beforehand?

Say I have a couple of basic objects like so:

[Serializable]
public class Base
{

    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

[Serializable]
public class Sub: Base
{
    public List<string> Property3 { get; set; }

    public Sub():base()
    {
        Property3 = new List<string>();
    }        
}

And I serialize them like so:

Sub s = new Sub {Property1 = "subtest", Property2 = 1000};
s.Property3.Add("item 1");
s.Property3.Add("item 2");

XmlSerializer sFormater = new XmlSerializer(typeof(Sub));
using (FileStream fStream = new FileStream("SubData.xml", 
    FileMode.Create, FileAccess.Write, FileShare.None))
{
    sFormater.Serialize(fStream, s);
}

How can I deserialize them, so that I get back the correct class?

As in, I'd want something like this

XmlSerializer bFormater = new XmlSerializer(typeof (Base));
Base newBase;
using (FileStream fStream = new FileStream("BaseData.xml", 
    FileMode.Open, FileAccess.Read, FileShare.Read))
{
    newBase = (Base) bFormater.Deserialize(fStream);
}

Except I'd be able to pass it an XML file for any class that descends from Base and the correct class would be created.

I'm thinking I could read the name of the root node of the XML and use a switch statement to create the correct XmlSerializer, but I was wondering if there was a simpler way.

like image 594
Ray Avatar asked Apr 22 '09 04:04

Ray


People also ask

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.

What is XML Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

What is XML ignore?

XmlIgnoreAttribute Class (System. Xml. Serialization) Instructs the Serialize(TextWriter, Object) method of the XmlSerializer not to serialize the public field or public read/write property value.


2 Answers

You can read the XML file's root node and instead of using a switch statement, you can write your code like this -

Type yourType = Type.GetType("Your Type");
XmlSerializer xs = new XmlSerializer(yourType);

I don't think there's any way other than reading the XML because if you don't know the type, you can't do anything.

like image 93
Kirtan Avatar answered Nov 08 '22 13:11

Kirtan


Use the [XmlInclude] attribute on your base class to tell the XML serializer about derived classes, so it can figure out what to create. Your last code snippet should then work correctly.

like image 30
Anton Tykhyy Avatar answered Nov 08 '22 11:11

Anton Tykhyy