关于XML序列化的简单例子

using System;
using System.IO;
using System.Xml.Serialization;

namespace SMSTest.Comm
{
    public class SerializeHelper
    {
        //序列化到xml文件  注意:文件将保存到应用程序同级目录
        public static bool Serialize(Type t,object tValue)
        {
            //序列化
            try
            {
                FileStream fs = new FileStream(t.ToString()+".xml", FileMode.Create);
                XmlSerializer xs = new XmlSerializer(t);
                xs.Serialize(fs, tValue);
                fs.Close();
                return true;
            }
            catch(Exception ex) 
            {
                return false;
            }
        }

        //从xml文件反序列化  注意:文件放在应用程序同级目录
        public static object DeSerialize(Type t)
        {
            if (!File.Exists(t.ToString() + ".xml")) return null;
            try
            {
                FileStream fs = new FileStream(t.ToString() + ".xml", FileMode.Open, FileAccess.Read);
                XmlSerializer xs = new XmlSerializer(t);
                return xs.Deserialize(fs);
            }
            catch (Exception e)
            {
                return null;
            }

        }
    }
}

注意要序列化的对象可以控制输出节点名称、样式、是否显示,方法如下:

[XmlRoot("CatsInfo")]  
public class CatCollection  
{  
    [XmlArray("Cats"), XmlArrayItem("Cat")]  
    public Cat[] Cats { get; set; }  
}  
  
[XmlRoot("Cat")]  
public class Cat  
{  
    // 定义Color属性的序列化为cat节点的属性  
    [XmlAttribute("color")]  
    public string Color { get; set; }  
  
    // 要求不序列化Speed属性  
    [XmlIgnore]  
    public int Speed { get; set; }  
  
    // 设置Saying属性序列化为Xml子元素  
    [XmlElement("saying")]  
    public string Saying { get; set; }  
}  
原文地址:https://www.cnblogs.com/tuyile006/p/605928.html