xml在程序开发中多用于数据储存或配置,在使用xml配置文件时,多会循环遍历xml节点然后在做处理,但是通常程序处理复杂可能不止一个循环, 为了提高程序运行效率,可以把xml反序列化成对象,这样不仅使用方便而且代码量少运行效率高。 <!--例xml--> <?xml version="1.0" encoding="UTF-8"?> <Table name="TA093_GTSJHS" excelIndex="0"> <Column name="TA093_13TKSSYL" type="numeric" length="9"/> <Column name="TA093_13TYHTKSYL" type="numeric" length="9"/> <Column name="TA093_13TKSHLL" type="numeric" length="5"/> <Column name="TA093_13GTRLSYL" type="numeric" length="9"/> <Column name="TA093_13TYHGTRLSYL" type="numeric" length="9"/> <Column name="TA093_13GTRLHLL" type="numeric" length="5"/> <Column name="TA093_13YQSJL" type="numeric" length="5"/> <Column name="TA093_13SO2SJL" type="numeric" length="5"/> </Table>//******************************************************************
//准备条件,按照xml文件节点编写实体类
/// <summary> /// xml文件Table节点类 /// </summary> [Serializable] [XmlRoot("Table")] public class Table { [XmlElement("Column")] public List<Column> list//Column节点 相当于table节点属性 在这作泛型 { get; set; } [XmlAttribute(AttributeName = "excelIndex")] public string excelIndex { get; set; } } /// <summary> /// xml文件column节点类 /// </summary> [Serializable]//指定该类是可序列化类 public class Column { [XmlAttribute(AttributeName = "name")]//该类成员序列化xml属性 public string name { get; set; } [XmlAttribute(AttributeName = "type")] public string type { get; set; } [XmlAttribute(AttributeName = "length")] public string length { get; set; } } /// <summary> /// xml反序列化 /// </summary> /// <param name="type">类型</param> /// <param name="xmlPath">XML字符串</param> /// <returns></returns> public static object Deserialize(Type type,string xmlPath) { try { using (StreamReader stream = new StreamReader(xmlPath)) { XmlSerializer xs = new XmlSerializer(type); return xs.Deserialize(stream); } } catch (Exception) { return null; } }
调用xml反序列化方法:Table obj= Deserialize(typeof(Table),xmlPath) as Table; //xml反序列化 表列集合
原文链接:https://www.f2er.com/xml/298028.html