作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有一个 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 provideGetSchema
too.
关于c# - 如何将动态对象序列化为xml C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757808/
我是一名优秀的程序员,十分优秀!