序列化部分DataContract

时间:2010-10-29 21:21:44

标签: wcf xsd datacontractserializer datamember

我的DataContract看起来像:

    [DataContract(Name = User.Root, Namespace = "")]
  public class RegisterUser
  {
    [DataMember(Name = User.EmailAddress)]
    public string EmailAddress { get; set; }
    [DataMember(Name = User.UserName)]
    public string UserName { get; set; }
    [DataMember(Name = User.Password)]
    public string Password { get; set; }
    [DataMember(Name = User.FirstName)]
    public string FirstName { get; set; }
    [DataMember(Name = User.LastName)]
    public string LastName { get; set; }
    [DataMember(Name = User.PhoneNumber)]
    public string PhoneNumber { get; set; }
    [DataMember(Name = "RequestMessage")]
    public string RequestMsg { get; set; }
  }

我想从中获取元素。而不是 <ROOT> <Element1/>...</ROOT>。我只想获得<Element1/>(对于部分xsd验证)。

我以为我可以使用这个功能:

public static string Serialize<T>(T obj)
{
  DataContractSerializer ser = new DataContractSerializer(obj.GetType());
  String text;
  using (MemoryStream memoryStream = new MemoryStream())
  {
    ser.WriteObject(memoryStream, obj);
    byte[] data = new byte[memoryStream.Length];
    Array.Copy(memoryStream.GetBuffer(), data, data.Length);
    text = Encoding.UTF8.GetString(data);
  }
  return text;
}

然后传递它

string str = Serialize(test.EmailAddress);

效果很好,但xml看起来像:

"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">myemail.com</string>"

我丢失了DataMember信息。我怎么能保留它?

1 个答案:

答案 0 :(得分:0)

使用WriteObjectContent而不是WriteObject: http://msdn.microsoft.com/en-us/library/ms573853.aspx