读取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 } }
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); }
3.调用
//读取xml实体
PLC_Xml XmlModel = PLC_VariableMgr.ReadXml_PLC(xml名称);
//初始化XML属性
Model model= PLC_VariableMgr.XmlToModel(XmlModel );