C#:包含泛型列表的类的 XML 序列化
我想知道是否有任何方法可以将包含泛型列表的类序列化为 xml? 它看起来像这样:
class Program
{
static void Main(string[] args)
{
var o = new ContainerClass();
o.Values = new List<SomeClass> {new SomeClass<int>(), new SomeClass<long>()};
XmlSerializer xs = new XmlSerializer(typeof(ContainerClass));
MemoryStream buffer = new MemoryStream();
using (TextWriter writer = new StreamWriter(buffer))
{
xs.Serialize(writer, o); // InvalidOperationException here
}
var xml = Encoding.UTF8.GetString(buffer.ToArray());
}
}
public class ContainerClass
{
public List<SomeClass> Values { get; set; }
}
public class SomeClass
{
}
public class SomeClass<T> : SomeClass
{
}
我知道有一种方法可以将额外的类型传递给序列化器,但现在没有办法传递可能出现的每种组合。
我尝试以各种方式实现 IXmlSerialized 但没有成功。
知道如何处理吗?
如果有任何可以处理它的外部库,我也开放。
I wonder if there is any way to serialize to xml a class that contains list of generics?
It looks like this:
class Program
{
static void Main(string[] args)
{
var o = new ContainerClass();
o.Values = new List<SomeClass> {new SomeClass<int>(), new SomeClass<long>()};
XmlSerializer xs = new XmlSerializer(typeof(ContainerClass));
MemoryStream buffer = new MemoryStream();
using (TextWriter writer = new StreamWriter(buffer))
{
xs.Serialize(writer, o); // InvalidOperationException here
}
var xml = Encoding.UTF8.GetString(buffer.ToArray());
}
}
public class ContainerClass
{
public List<SomeClass> Values { get; set; }
}
public class SomeClass
{
}
public class SomeClass<T> : SomeClass
{
}
I know that there is a way to pass extra types to the serializer, but there is no way to now every combination that could probably appear.
I've tried to implement IXmlSerializable i various ways without success.
Any idea how to deal with it?
I am also open for external libraries if there is any that can handle it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现 YAXLib 可以完成这项工作。
I've found YAXLib which does the job.
在尝试了几个库之后,我决定编写自己的代码:
Atlas Xml Serializer
获取 binaries 文件夹下的 dll 并将其添加到您的项目中。然后您的代码应该像这样工作:
输出将类似于:
PS:WinformsTestApp 是我的测试应用程序名称,因此它将更改以反映您的程序集名称。
After trying few libraries, I decided to code my own:
Atlas Xml Serializer
Get the dll under binaries folder and add it to your project. Then your code should work like this:
Output will be similar to this:
PS: WinformsTestApp is my test appilcations name, so it'll change to reflect your assembly name.