想实现:C#读取XML文件内的内容至List
XML文件:AppAttr.xml 其中,一定是要ArrayOfAppAttr(红色部分AppAttr为你的实体类名)
<?xml version="1.0" encoding="utf-8" ?> <ArrayOfAppAttr xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <AppAttr> <Key>FileFolder</Key> <Value>C:/PWFileVersion</Value> </AppAttr> <AppAttr> <Key>CallAddress</Key> <Value>pwfileversion://</Value> </AppAttr> </ArrayOfAppAttr>
实体类文件:AppAttr
[Serializable]//不能忘记 public class AppAttr { public AppAttr() { } public AppAttr(string K, string V) { Key = K; Value = V; } public string Key; public string Value; }
序列化类:XmlSerialize
class XmlSerialize { /// <summary> /// 反序列化XML为类实例 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xmlObj"></param> /// <returns></returns> public static T DeserializeXml<T>(string xmlObj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xmlObj)) { return (T)serializer.Deserialize(reader); } } /// <summary> /// 序列化类实例为XML /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string SerializeXml<T>(T obj) { using (StringWriter writer = new StringWriter()) { new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj); return writer.ToString(); } } }
程序运行进行读取
List<AppAttr> appAttrList = null; XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<AppAttr>)); //_configPath为你的xml配置文件位置 using (StreamReader streamReader = new StreamReader(_configPath)) { appAttrList = xmlSerializer.Deserialize(streamReader) as List<AppAttr>; }
参考:
时间: 2024-12-09 05:50:53