Search code examples
c#xmlxml-serializationxmlserializerdynamicobject

How to serialize dynamic object to xml c#


I have a object {System.Collections.Generic.List<object>} that contains 1000 object {DynamicData} inside of it, each one with 4 keys and values and one more List with 2 keys and values inside. I need to serialize this object into a XML File, i tried normal serialization but it gives me this exception = The type DynamicData was not expected, how can i serialize this object?

Here is the code:

           //output is the name of my object
            XmlSerializer xsSubmit = new XmlSerializer(output.GetType());
            var xml = "";

            using (var sww = new StringWriter())
            {
                using (XmlWriter writers = XmlWriter.Create(sww))
                {
                    try
                    {
                        xsSubmit.Serialize(writers, output);
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                    xml = sww.ToString(); // Your XML
                }
            }

I can create the xml file writing line by line and element by element, but i want something more faster and with less code. The structure of my object is like this:

output (count 1000)
 [0]
   Costumer - "Costumername"
   DT - "Date"
   Key - "Key"
   Payment - "x"
   [0]
    Adress - "x"
    Number - "1"
 [1]...
 [2]...

Solution

  • You can implement your own serialize object by using IXmlSerializable

    [Serializable]
    public class ObjectSerialize :  IXmlSerializable
    {
        public List<object> ObjectList { get; set; }
    
        public XmlSchema GetSchema()
        {
            return new XmlSchema();
        }
    
        public void ReadXml(XmlReader reader)
        {
    
        }
    
        public void WriteXml(XmlWriter writer)
        {
            foreach (var obj in ObjectList)
            {   
                //Provide elements for object item
                writer.WriteStartElement("Object");
                var properties = obj.GetType().GetProperties();
                foreach (var propertyInfo in properties)
                {   
                    //Provide elements for per property
                    writer.WriteElementString(propertyInfo.Name, propertyInfo.GetValue(obj).ToString());
                }
                writer.WriteEndElement();
            }
        }
    }
    

    Usage;

            var output = new List<object>
            {
                new { Sample = "Sample" }
            };
            var objectSerialize = new ObjectSerialize
            {
                ObjectList = output
            };
            XmlSerializer xsSubmit = new XmlSerializer(typeof(ObjectSerialize));
            var xml = "";
    
            using (var sww = new StringWriter())
            {
                using (XmlWriter writers = XmlWriter.Create(sww))
                {
                    try
                    {
                        xsSubmit.Serialize(writers, objectSerialize);
                    }
                    catch (Exception ex)
                    {
    
                        throw;
                    }
                    xml = sww.ToString(); // Your XML
                }
            }
    

    Output

    <?xml version="1.0" encoding="utf-16"?>
    <ObjectSerialize>
        <Object>
            <Sample>Sample</Sample>
        </Object>
    </ObjectSerialize>
    

    Note : Be careful with that, if you want to deserialize with same type (ObjectSerialize) you should provide ReadXml. And if you want to specify schema, you should provide GetSchema too.