Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize dynamic object to xml c#

Tags:

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]...
like image 777
Lucio Zenir Avatar asked Dec 11 '17 17:12

Lucio Zenir


People also ask

What is XML serialization?

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.

What is XmlSerializer in c#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.


1 Answers

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.

like image 127
lucky Avatar answered Oct 13 '22 13:10

lucky