C#反序列化XML
-
序列化反序列化的概念
seriallization 序列化 : 将对象转化为便于传输的格式, 常见的序列化格式:二进制格式,字节数组,json字符串,xml字符串。
deseriallization 反序列化:将序列化的数据恢复为对象的过程。 -
Xml字符串反序列化为对象
使用ADO.Net连接数据库查询到对应的字段下的XML字符串(贴一段代码)//创建连接对象,并使用using释放(关闭),连接用完后会被自动关闭 using (SqlConnection conn = new SqlConnection("server=.;uid=*****;pwd=******;database=Lg_ExamRec_A")) { //打开连接 conn.Open(); //将执行的sql String sql = "select * from LgExamQues_New where QuesType='单选题'"; //创建命令对象,指定要执行sql语句与连接对象conn SqlCommand cmd = new SqlCommand(sql, conn); //执行查询返回结果集 SqlDataReader sdr = cmd.ExecuteReader(); TContent quesSource = new TContent(); //下移游标,读取一行,如果没有数据了则返回false while (sdr.Read()) { string tp = sdr["QuesType"].ToString().Trim(); if (tp == "单选题") { Console.WriteLine("---------------------------------------查询到的Xml文档-------------------------------"); Console.WriteLine("题型来源:" + sdr["QuesSourceXml"]); Console.WriteLine("---------------------------------------对应的反序列化结果为:--------------------------------------"); string str = sdr["QuesSourceXml"].ToString(); quesSource = XmlSerialize.DeserializeXML<TContent>(str); Console.WriteLine("编号:" + sdr["ID"]); Console.WriteLine("题型:" + sdr["QuesType"]); Console.WriteLine("题型编号:" + sdr["QuesTypeCode"]); foreach (var item in quesSource.QuesChild) { //Console.WriteLine("分数:" + item.QuesScore.text); foreach (var item1 in item.QuesOption) { Console.WriteLine("选项:" + item1.text); } } } } Console.ReadLine(); }
-
public static T DeserializeXML<T>(string xmlObj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xmlObj)) { return (T)serializer.Deserialize(reader); } }
-
1.建立对应类的时候注意节点要和类名一致 2.注意父节点与子节点的包含关系 3.注意节点与类型之间的关系
具体可参考:https://www.cnblogs.com/guogangj/p/7489218.html
https://www.cnblogs.com/bdstjk/archive/2012/01/19/2519860.html
https://blog.csdn.net/bdstjk/article/details/7210742
https://docs.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-xml-serialization?view=netframework-4.8
posted on 2019-07-24 15:55 NoMatterTryAgain 阅读(390) 评论(0) 编辑 收藏 举报