需求
将XML文件中的数据经过转换后插入到数据库中。
参考
C#实体类和XML的相互转换
https://blog.csdn.net/pan_junbiao/article/details/82938027
遇到的问题
错误描述
XML反序列化出错,XML 文档(2, 2)中有错误
解决方案
在实体类的字段要加上XmlElement属性
https://www.cnblogs.com/wuyunblog/p/6625747.html
具体实例
实体类和XML转换的帮助类
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Xml.Serialization; 8 9 namespace conDealXML 10 { 11 public static class XmlSerializeHelper 12 { 13 14 /// <summary> 15 /// 将实体对象转换成XML 16 /// </summary> 17 /// <typeparam name="T">实体类型</typeparam> 18 /// <param name="obj">实体对象</param> 19 public static string XmlSerialize<T>(T obj) 20 { 21 try 22 { 23 using (StringWriter sw = new StringWriter()) 24 { 25 Type t = obj.GetType(); 26 XmlSerializer serializer = new XmlSerializer(obj.GetType()); 27 serializer.Serialize(sw, obj); 28 sw.Close(); 29 return sw.ToString(); 30 } 31 } 32 catch (Exception ex) 33 { 34 throw new Exception("将实体对象转换成XML异常", ex); 35 } 36 } 37 38 /// <summary> 39 /// 将XML转换成实体对象 40 /// </summary> 41 /// <typeparam name="T">实体类型</typeparam> 42 /// <param name="strXML">XML</param> 43 public static T DESerializer<T>(string strXML) where T : class 44 { 45 try 46 { 47 using (StringReader sr = new StringReader(strXML)) 48 { 49 XmlSerializer serializer = new XmlSerializer(typeof(T)); 50 return serializer.Deserialize(sr) as T; 51 } 52 } 53 catch (Exception ex) 54 { 55 throw new Exception("将XML转换成实体对象异常", ex); 56 } 57 58 } 59 } 60 }