xml序列化

public static void SaveToXml(string filePath, object sourceObj, Type type, string xmlRootName)
        {
            if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
            {
                type = type != null ? type : sourceObj.GetType();

                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
                        new System.Xml.Serialization.XmlSerializer(type) :
                        new System.Xml.Serialization.XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                    xmlSerializer.Serialize(writer, sourceObj);
                }
            }
        }

        public static object LoadFromXml(string filePath, Type type)
        {
            object result = null;

            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
                    result = xmlSerializer.Deserialize(reader);
                }
            }

            return result;
        }



//主类特性
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
   
//属性特性
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("AirLineCompany")]
//序列化指定特定的节点名称 
[System.Xml.Serialization.XmlType("AirLine")] public class Ret_AirLine { public string DepartureAirport { get; set; } public string ArrivalAirport { get; set; } /// <summary> /// PassengerName PassengerType IdNo KeepFee ReturnMoney /// </summary> public List<Passenger> PassengerList { get; set; } = new List<Passenger>(); }

  

  

  

原文地址:https://www.cnblogs.com/guosier/p/5681069.html