日期:2014-05-18  浏览次数:20992 次

纠结了两天的DataContractSerializer 反序列化xml的问题,在线等啊
xml格式Contract
string data = 
"<Contract xmlns=\"http://tianka.com\">
<Title>合同版权</Title>

<Copyrights> //一个合同里面有多个版权实体
<Copyright ><WorksName>青色平原</WorksName></Copyright> 
<Copyright ><WorksName>西游记</WorksName></Copyright>
</Copyrights>

</Contract>";

下面是DataContract契约类

//合同类
[DataContract(Namespace = "http://tianka.com")]
  public class Contract
  {
  [DataMember]
  public int Title{ get;set;}

  private List<Copyright> m_copyrights = new List<Copyright>();
  [DataMember]
  public List<Copyright> Copyrights
  {
  get
  {
  return this.m_copyrights;
  }
  set
  {
  this.m_copyrights = value;  
  }
  }
  }

//版权类
  [DataContract]
  public class Copyright
  {
  [DataMember]
  public string WorksName { get; set; }

  }

问题:

  //反序列化为对象
  byte[] bytes = UnicodeEncoding.UTF8.GetBytes(data);
  DataContractSerializer xml = new DataContractSerializer(typeof(Contract));
  MemoryStream ms = new MemoryStream(bytes);
  Contract c = (Contract)xml.ReadObject(ms);

  序列化完之后c.Copyrights总是为null.请高手解答。

------解决方案--------------------
你的XML可能有问题,如果记得没错,集合类用DataContract是会多一层节点出来的。

你直接把你的类‘正序列化’之后,和你的XML对比一下就知道了
------解决方案--------------------
帮lz试了一把
C# code

class Program {
    static void Main(string[] args) {
        //var c = new Contract {
        //    Title = "合同版权",
        //    Copyrights = new List<Copyright> { 
        //        new Copyright{WorksName="worksname1"},
        //        new Copyright{WorksName="worksname2"},
        //        new Copyright{WorksName="worksname3"}
        //    }
        //};

        //using (MemoryStream ms = new MemoryStream()) {
        //    var xs = new XmlSerializer(typeof(Contract));
        //    xs.Serialize(ms, c);
        //    Console.WriteLine(Encoding.UTF8.GetString(ms.GetBuffer()));
        //}

        string data = "<Contract><Title>合同版权</Title><Copyrights><Copyright ><WorksName>青色平原</WorksName></Copyright><Copyright><WorksName>西游记</WorksName></Copyright></Copyrights></Contract>";
        var xs = new XmlSerializer(typeof(Contract));
        var c = xs.Deserialize(new StringReader(data)) as Contract;
        Console.WriteLine(c.Copyrights.Count);
        foreach(var each in c.Copyrights){
            Console.WriteLine(each.WorksName);
        }

        Console.WriteLine("press any key to exit.");
        Console.ReadLine();
    }
}

[DataContract]
public class Contract {
    [DataMember]
    public string Title { get; set; }

    private List<Copyright> m_copyrights = new List<Copyright>();
    [DataMember]
    public List<Copyright> Copyrights {
        get { return this.m_copyrights; }
        set { this.m_copyrights = value; }
    }
}

//版权类
[DataContract]
public class Copyright {
    [DataMember]
    public string WorksName { get; set; }

}

------解决方案--------------------
1. 指定次序(默认C在T前面,而Copyrights在Title后面):
[DataMember(Order=1