gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:28:42 25 4
gpt4 key购买 nike

我有一个 object {System.Collections.Generic.List<object>}包含 1000 object {DynamicData}在里面,每个都有 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]...

最佳答案

您可以使用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>

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.

关于c# - 如何将动态对象序列化为xml C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com