博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

序列化和发序列化

Posted on 2014-01-13 15:37  随遇  阅读(131)  评论(0)    收藏  举报

1.xml 文档序列化成对象

public static ContactDetails Deserialize(string proposalsXml)
{
  try
  {
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(ContactDetails));
    TextReader reader = new StringReader(proposalsXml);
    return xmlSerializer.Deserialize(reader) as ContactDetails;
  }
  catch
  {
    throw;
  }
}

/// <summary>
/// Serialize the current object to a string.
/// </summary>
/// <returns></returns>
public string Serialize()
{
  XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
  XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
  //Add an empty namespace and empty value
  ns.Add("", "");
  StringBuilder stringBuilder = new StringBuilder();
  StringWriterWithEncoding textWriter = new StringWriterWithEncoding(stringBuilder, Encoding.UTF8);
  xmlSerializer.Serialize(textWriter, this,ns);
  return stringBuilder.ToString();
}

 

ContactDetails result;
XmlSerializer ser = new XmlSerializer(typeof(ContactDetails));
using (TextReader tr = new StringReader(xmlResult.OuterXml.Replace("T00:00:00", string.Empty)))
{
result = (ContactDetails)ser.Deserialize(tr);
}
return result;