1 序列化方法
public void SerializeObject<T>(string Xmlname,T t) { XmlSerializer ser = new XmlSerializer(typeof(T)); TextWriter writer = new StreamWriter(Xmlname); ser.Serialize(writer, t);//要序列化的对象 writer.Close(); }
2 序列化方法的使用
NodeConfigInfo nc = new NodeConfigInfo(); nc.FirstNodeSql = this.textBoxSqlFirstNode.Text.Trim(); nc.FirstArticleSql = this.textBoxViewFirArtlcle.Text.Trim(); nc.SecondNodeSql = this.textBoxSqlSecondNode.Text.Trim(); nc.SecondArticleSql = this.textBoxViewSecArtlcle.Text.Trim(); nc.SecondNodeFilter = this.textBoxSecFilter.Text.Trim(); nc.SecondArticleFilter = this.textBoxSecFilter.Text.Trim(); nc.SecondNodeDefaultParentId = this.textBoxParentDefault.Text.Trim(); nc.ConnectionOther = this.textBoxConnection.Text.Trim(); nc.NodeId = this.textBoxParentId.Text.Trim(); nc.SecondReFilter = this.textBoxReFilterSec.Text.Trim(); string xmlName = System.IO.Directory.GetCurrentDirectory() + "\" + typeof(NodeConfigInfo).Name + ".Config"; SerializeObject<NodeConfigInfo>(xmlName, nc);
3 序列化的类
public class NodeConfigInfo { public string FirstNodeSql { get; set; } public string FirstArticleSql { get; set; } public string SecondNodeSql { get; set; } public string SecondArticleSql { get; set; } public string SecondNodeFilter { get; set; } public string SecondArticleFilter { get; set; } public string SecondNodeDefaultParentId { get; set; } public string ConnectionOther { get; set; } public string NodeId { get; set; } public string SecondReFilter { get; set; } }
4 反序列化方法
public T DeSerializeObject<T>() { string xmlName = System.IO.Directory.GetCurrentDirectory() + "\" + typeof(T).Name + ".Config"; FileStream file = new FileStream(xmlName, FileMode.Open, FileAccess.Read); XmlSerializer xmlSearializer = new XmlSerializer(typeof(T)); T info = (T)xmlSearializer.Deserialize(file); file.Close(); file.Dispose(); return info; }
5 反序列化方法的使用
//xml来源可能是外部文件,也可能是从其他系统获得 NodeConfigInfo info = DeSerializeObject<NodeConfigInfo>(); this.textBoxSqlFirstNode.Text = info.FirstNodeSql; this.textBoxViewFirArtlcle.Text = info.FirstArticleSql; this.textBoxSqlSecondNode.Text = info.SecondNodeSql; this.textBoxViewSecArtlcle.Text = info.SecondArticleSql; this.textBoxSecFilter.Text = info.SecondNodeFilter; this.textBoxSecFilter.Text = info.SecondArticleFilter; this.textBoxParentDefault.Text = info.SecondNodeDefaultParentId; this.textBoxConnection.Text = info.ConnectionOther; this.textBoxParentId.Text = info.NodeId; this.textBoxReFilterSec.Text = info.SecondReFilter;