问题描述
这是一个有点长的问题,但我做了它的简洁越好,所以请多多包涵。它看起来对我来说,在的XmlSerializer
类的错误,但之前,我与微软提交它,我想看看是否有什么我已经错过了,这是完全有可能的。
This is a bit of a long question, but I've made it as terse as possible, so please bear with me. It looks to me like a bug in the XmlSerializer
class but before I file it with Microsoft I'd like to see if there's anything I've missed, which is entirely possible.
我试图生成下面的XML作为再presentative情况下,这基本上是集合的集合,但其中外部集合具有附加元素:
I'm attempting to generate the following XML as a representative case, which is essentially a collection of collections, but where the outer collection has additional elements:
<Links>
<Name />
<Group>
<Link />
<Link />
</Group>
<Group>
<Link />
<Link />
</Group>
</Links>
序列化类如下:
The serialization classes are as follows:
public class Link { }
public class Links
{
public string Name { get; set; }
[XmlElement("Group")]
public Link[][] Groups { get; set; }
}
和一个简单的测试程序来运行其计算方法如下:
And a simple test program to run it is as follows:
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(Links));
var links = new Links { Name = "", Groups = new[] {
new[] { new Link(), new Link() },
new[] { new Link(), new Link() } } };
serializer.Serialize(Console.Out, links);
}
}
本使用的伎俩using 的XmlElement
删除集合的父节点,这应该意味着没有&LT;组&GT;
元素被发射,并且包含在外部阵列(这将是类型链接[]
)的每个对象中的&LT;组&gt;
元素发射。然而,在运行时,这给从下列异常的XmlSerializer
:
This employs the trick of using XmlElement
to remove the parent node of the collection, which should mean that no <Groups>
element is emitted, and for each object contained in the outer array (which will be of type Link[]
) a <Group>
element should be emitted. However, at runtime, this gives the following exception from the XmlSerializer
:
无法生成临时类(结果= 1)。 错误CS0030:无法将类型'链接[] []'到'链接[]' 错误CS0029:无法隐式转换类型'链接[]'到'链接[] []
我的猜测是,序列化是由于某种原因,试图压平的收集,并认为含有外阵列中的类型是链接
,而不是链接[]
导致其序列化类的编译失败的类型不匹配。
My guess is that the serializer is for some reason attempting to flatten the collection, and thinks that the type contained in the outer array is Link
rather than Link[]
which causes the compilation failure of its serialization classes as the types don't match.
你怎么看?这是一个错误?而且有一种变通方法来生成我使用后很XML中的的XmlSerializer
?
What do you think? Is this a bug? And is there a workaround to generate the XML I'm after using the XmlSerializer
?
推荐答案
我会建议写一个XML模式,它定义了你想要在你的XML和比使用从其生成相应的序列化code的语法code生成工具(如MS XSD.EXE)。写一个架构是数据验证的好方法呢。即使你不打算用它,而是希望维持Ç自己的$ C $,你至少可以看看生成的code。
I would suggest writing an XML schema, which defines the syntax you want to have in your XML and than generate the corresponding serialization code from it using a code generation tool (e.g. MS xsd.exe).Writing a schema is a good approach for data validation anyway. Even if you do not want to use it later and rather want to maintain the code yourself, you can at least have a look at the generated code.
这篇关于XmlSerializer的错误时,序列化收集藏品没有根元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!