如何将动态对象序列化为xml c#

时间:2017-12-11 17:03:55

标签: c# xml xml-serialization xmlserializer dynamicobject

我有一个object {System.Collections.Generic.List<object>},里面包含1000 object {DynamicData},每个{4}包含4个键和值,还有一个List,其中包含2个键和值。 我需要将此对象序列化为XML文件,我尝试了正常的序列化,但它给了我这个异常= The type DynamicData was not expected,我如何序列化这个对象?

以下是代码:

           //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
                }
            }

我可以创建逐行逐行写入的xml文件,但我想要更快更快的代码。 我的对象的结构是这样的:

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

1 个答案:

答案 0 :(得分:2)

您可以使用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();
        }
    }
}

<强>用法

        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
            }
        }

<强>输出

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

注意:如果要使用相同类型反序列化,请注意   (ObjectSerialize)你应该提供ReadXml。如果你愿意的话   指定架构,您也应该提供GetSchema