我有一个看起来像的 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 信息。我怎样才能保留它呢?