• 读取xml文件到实体


    1.变量基本属性及反序列化

    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    
    namespace Xml.Model
    {
        [XmlRoot(ElementName = "PLC")]
       public class PLC_Xml
        {
            [XmlElement(ElementName = "Variable")]
            public List<PLC_Variable> VarlstFromXml_PLC { get; set; }
        }
        public class PLC_Variable
        {
            [XmlElement(ElementName = "Name")]
            public string Name { get; set; }
    
            [XmlElement(ElementName = "Adress")]
            public string Adress { get; set; }
    
            [XmlElement(ElementName = "Type")]
            public string Type { get; set; }
    
            [XmlElement(ElementName = "Length")]
            public string Length { get; set; }
    
        }
     public class XMLDeseralize
        {
            #region 方法:xml反序列化
    
            //反序列化
            //接收2个参数:xmlFilePath(需要反序列化的XML文件的绝对路径),type(反序列化XML为哪种对象类型)
            /// <summary>
            /// xml反序列化
            /// </summary>
            /// <param name="xmlFilePath">需要反序列化的XML文件名(相对路径)</param>
            /// <param name="type">反序列化XML为哪种对象类型</param>
            /// <returns></returns>
            public static object DeserializeFromXml(string rootName, Type type)
            {
                try
                {
                    object result = null;
                    string path = Application.StartupPath + "\xml" + "\" + rootName + ".xml";
                    if (File.Exists(path))
                    {
                        using (StreamReader reader = new StreamReader(path))
                        {
                            XmlSerializer xs = new XmlSerializer(type);
                            result = xs.Deserialize(reader);
                        }
                    }
                    return result;
                }
                catch (Exception ex)
                {
    
                    throw ex;
                }
            }
            #endregion
        }
    }
    View Code

    2.xml的读取

    public static PLC_Xml ReadXml_PLC(string xmlName)
    {
    PLC_Xml test = new PLC_Xml();
    object c = XMLDeseralize.DeserializeFromXml(xmlName, typeof(PLC_Xml)) as PLC_Xml;
    return test = (c as PLC_Xml);
    }
    View Code

    3.调用

    //读取xml实体
    PLC_Xml XmlModel = PLC_VariableMgr.ReadXml_PLC(xml名称);

    //初始化XML属性
    Model model= PLC_VariableMgr.XmlToModel(XmlModel );

  • 相关阅读:
    DJANGO入门系列之(模型层:跨表操作)
    DJANGO入门系列之(模型层:单表操作)
    DJANGO入门系列之(模板层)
    DJANGO入门系列之(视图层)
    DJANGO入门系列之(模板层的简单介绍和视图层的扫尾)
    DJANGO入门系列之(虚拟环境的配置与安装)
    Django入门系列之(视图层基本概念)
    DJANGO入门系列之(路由控制)
    DJANGO入门系列之(Django请求生命周期and路由层)
    orm
  • 原文地址:https://www.cnblogs.com/mamaxiaoling/p/8417383.html
Copyright © 2020-2023  润新知