首页 > 其他 > 详细

XML序列化

时间:2020-02-22 22:35:37      阅读:62      评论:0      收藏:0      [点我收藏+]
namespace WindowsFormsUCMP
{
    [XmlRoot("Setup")]
    [Serializable]    
    public class Users
    {

        public string username = "admin";
        public string password = "";
        public string remember = "";
        //public Users() { }
        public override string ToString()
        {
            return $"[username={username}, password={password}, remember={remember}]";
        }
    }

    [Serializable]
   
    public class CServer
    {

        public string add = "localhost";
        public bool remember = false;

        public override string ToString()
        {
            return $"[address={add},remember={remember}]";
        }
    }
    

    public class xml_serializer_manager
    {

        public void serialize_to_xml(string path, object obj)
        {

            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            string content = string.Empty;
            //serialize
            //using (StringWriter fs = new StringWriter())
            //{
            //    serializer.Serialize(fs, obj);                                
            //    content = fs.ToString();
            //    //fs.Write(content);
            //}
            //using (StreamWriter stream_writer = new StreamWriter(path))
            //{
            //    stream_writer.Write(content);
            //}
                //fs.Write(content);

            using (FileStream fs = new FileStream(path,FileMode.OpenOrCreate))
            {
                serializer.Serialize(fs, obj);
                fs.Close();
            }
            //save to file
        }

        /// <summary>
        /// deserialize xml file to object
        /// </summary>
        /// <param name="path">the path of the xml file</param>
        /// <param name="object_type">the object type you want to deserialize</param>
//反序列化
public object deserialize_from_xml(string path, Type object_type) { XmlSerializer serializer = new XmlSerializer(object_type); using (StreamReader reader = new StreamReader(path)) { return serializer.Deserialize(reader); } } } }

 

XML序列化

原文:https://www.cnblogs.com/hardenzhao/p/12347385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!