zoukankan      html  css  js  c++  java
  • 读取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 );

  • 相关阅读:
    推销
    5132. 颜色交替的最短路径
    5130. 等价多米诺骨牌对的数量
    @babel/plugin-transform-runtime和@babel/preset-env的区别
    5128. 最深叶节点的最近公共祖先(二叉树)
    1094. 拼车
    1109. 航班预订统计(数组)
    5129. 表现良好的最长时间段(数组)
    path.resove 和 path.join
    【原生】 call、apply、bind 的基本使用方法,已经解析了某些源码
  • 原文地址:https://www.cnblogs.com/mamaxiaoling/p/8417383.html
Copyright © 2011-2022 走看看