在反序列化时,是否可以使用XmlSerializer忽略已定义的元素顺序?我在序列化时需要严格的排序,但是希望在反序列化时放宽规则。
public class Foo()
{
[XmlElement("Prop1", Order = 1)]
public string Prop1 { get; set; }
[XmlElement("Prop2", Order = 2)]
public string Prop2 { get; set; }
}
更新
对于那些不了解问题的人,以下是行为:
鉴于此xml:
<MyObject>
<Name>Test</Name>
<Foo>
<Prop2>prop 2</Prop2>
<Prop1>prop 1</Prop1>
</Foo>
</MyObject>
和这些类:
[XmlRoot("MyObject")]
public class MyObject
{
[XmlElement("Name", Order = 1)]
public string Name { get; set; }
[XmlElement("Foo", Order = 2)]
public Foo[] Foos { get; set; }
}
public class Foo
{
[XmlElement("Prop1", Order = 1)]
public string Prop1 { get; set; }
[XmlElement("Prop2", Order = 2)]
public string Prop2 { get; set; }
}
反序列化时,无法初始化Prop1:
var xmlSerializer = new XmlSerializer(typeof(MyObject));
MyObject myobject = null;
using (var reader = new StringReader(xml))
{
myobject = xmlSerializer.Deserialize(reader) as MyObject;
}
如果属性在XML中以定义的顺序存在,那就没问题了。