请问顺序很重要的XML阅读由DataContractSerializer的? [英] Does Order Matter in the XML Read by the DataContractSerializer?
本文介绍了请问顺序很重要的XML阅读由DataContractSerializer的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的code:
[DataContract(Namespace = "")]
public class User
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string FullName { get; set; }
}
//Deserialization test
public void Test()
{
//CASE 1.
//string xml = "<User><UserName>john</UserName>" +
// "<FullName>John Lennon</FullName></User>";
//CASE 2.
string xml = "<User><FullName>John Lennon</FullName>" +
"<UserName>john</UserName></User>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
User user = null;
using (MemoryStream stream = new MemoryStream(byteArray))
{
DataContractSerializer serializer =
new DataContractSerializer(typeof(User), "User", "");
user = (User)serializer.ReadObject(stream);
}
}
在情况1,全名属性不反序列化,但万一二是正确的反序列化。为什么呢?
In case 1, FullName property isn't deserialized, but in case 2 it is deserialized properly. Why?
推荐答案
由于顺序是显著。按字母顺序使用,除非你在你的DataMember属性指定的顺序。
Because order is significant. Alphabetic order is used unless you specify the order in your DataMember attributes.
这是在<一个解释href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.order.aspx">this MSDN文章。
在一般情况下,这是对你的数据成员总是显式地指定订购一个很好的做法属性:
In general, it's a good practice to always explicitly specify Order on your DataMember attributes:
[DataMember(IsRequired=true, Order=0)]
public string FullName { get; set; }
[DataMember(IsRequired=true, Order=1)]
public string UserName { get; set; }
这篇关于请问顺序很重要的XML阅读由DataContractSerializer的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文