1. 程式人生 > 其它 >C# 將實體轉xml/xml轉實體

C# 將實體轉xml/xml轉實體

xml轉實體

 /// <summary>
        /// 把xml轉換成實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static List<T> GetXmlModel<T>(T model, string
xmlString) where T : class { List<T> list = new List<T>(); try { XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlString);//把xml格式的字串轉為XMLDataDocument物件 XmlNodeList data = xml.DocumentElement.ChildNodes;//
得到的是xml物件的節點陣列 foreach (XmlNode item in data) { Dictionary<string, string> xmlDic = new Dictionary<string, string>(); if (item.ChildNodes.Count > 0) { foreach (XmlNode it in
item.ChildNodes) { xmlDic.Add(it.LocalName, it.InnerText); } } var m = model.GetType(); foreach (PropertyInfo p in m.GetProperties()) { string name = p.Name; if (xmlDic.Keys.Contains(name)) { string value = xmlDic.Where(x => x.Key == name).FirstOrDefault().Value; p.SetValue(model, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, p.PropertyType), null); } } list.Add(model); } return list; } catch (Exception ex) { return list; } }

實體轉xml

/// <summary>
        /// 地圖檔案 - 實體轉xml
        /// </summary>
        /// <param name="patrolEquipmentDto"></param>
        /// <param name="path"></param>
        private static void MapFileToXmlMethod(List<LinkageConfigFileDto> patrolEquipmentDto, string path)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //加入XML的宣告段落,Save方法不再xml上寫出獨立屬性
            xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
            //加入根元素

            XmlElement root = xmlDoc.CreateElement("Effect_Config");
            xmlDoc.AppendChild(root);

            foreach (var item in patrolEquipmentDto)
            {
                XmlElement memberlist = xmlDoc.CreateElement("Item");
                XmlElement source_code = xmlDoc.CreateElement("source_code");
                source_code.InnerText = item?.source_code;

                XmlElement source_name = xmlDoc.CreateElement("source_name");
                source_name.InnerText = item?.source_name;

                XmlElement source_type = xmlDoc.CreateElement("source_type");
                source_type.InnerText = item?.source_type;

                XmlElement device_id = xmlDoc.CreateElement("device_id");
                device_id.InnerText = item?.device_id;

                memberlist.AppendChild(source_code);
                memberlist.AppendChild(source_name);
                memberlist.AppendChild(source_type);
                memberlist.AppendChild(device_id);
                root.AppendChild(memberlist);
            }
            xmlDoc.Save(path);
        }