您好,欢迎访问一九零五行业门户网

用C#实现XML和实体类之间序列化和反序列化相互转换

using system; using system.collections.generic; using system.linq; using system.text; using system.io; using system.data; using system.xml; using system.xml.serialization; /// <summary> /// xml序列化与反序列化 /// </summary> public class xmlutil { #region 反序列化 /// <summary> /// 反序列化 /// </summary> /// <param name="type">类型</param> /// <param name="xml">xml字符串</param> /// <returns></returns> public static object deserialize(type type, string xml) { try { using (stringreader sr = new stringreader(xml)) { xmlserializer xmldes = new xmlserializer(type); return xmldes.deserialize(sr); } } catch (exception e) { return null; } } /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static object deserialize(type type, stream stream) { xmlserializer xmldes = new xmlserializer(type); return xmldes.deserialize(stream); } #endregion #region 序列化 /// <summary> /// 序列化 /// </summary> /// <param name="type">类型</param> /// <param name="obj">对象</param> /// <returns></returns> public static string serializer(type type, object obj) { memorystream stream = new memorystream(); xmlserializer xml = new xmlserializer(type); try { //序列化对象 xml.serialize(stream, obj); } catch (invalidoperationexception) { throw; } stream.position = 0; streamreader sr = new streamreader(stream); string str = sr.readtoend(); sr.dispose(); stream.dispose(); return str; } #endregion } /* 实体对象转换到xml */ public class student { public string name { set; get; } public int age { set; get; } } student stu1 = new student() { name = "okbase", age = 10 }; string xml = xmlutil.serializer(typeof(student), stu1); console.write(xml); /* xml转换到实体对象 */ student stu2 = xmlutil.deserialize(typeof(student), xml) as student; console.write(string.format("名字:{0},年龄:{1}", stu2.name, stu2.age)); /* datatable转换到xml */ // 生成datatable对象用于测试 datatable dt1 = new datatable("mytable"); // 必须指明datatable名称 dt1.columns.add("dosage", typeof(int)); dt1.columns.add("drug", typeof(string)); dt1.columns.add("patient", typeof(string)); dt1.columns.add("date", typeof(datetime)); // 添加行 dt1.rows.add(25, "indocin", "david", datetime.now); dt1.rows.add(50, "enebrel", "sam", datetime.now); dt1.rows.add(10, "hydralazine", "christoff", datetime.now); dt1.rows.add(21, "combivent", "janet", datetime.now); dt1.rows.add(100, "dilantin", "melanie", datetime.now); // 序列化 xml = xmlutil.serializer(typeof(datatable), dt1); console.write(xml); /* xml转换到datatable */ // 反序列化 datatable dt2 = xmlutil.deserialize(typeof(datatable), xml) as datatable; // 输出测试结果 foreach (datarow dr in dt2.rows) { foreach (datacolumn col in dt2.columns) { console.write(dr[col].tostring() + " "); } console.write("\r\n"); } /* list转换到xml */ // 生成list对象用于测试 list<student> list1 = new list<student>(3); list1.add(new student() { name = "okbase", age = 10 }); list1.add(new student() { name = "csdn", age = 15 }); // 序列化 xml = xmlutil.serializer(typeof(list<student>), list1); console.write(xml); /* xml转换到list */ list<student> list2 = xmlutil.deserialize(typeof(list<student>), xml) as list<student>; foreach (student stu in list2) { console.writeline(stu.name + "," + stu.age.tostring()); } protected void page_load(object sender, eventargs e) { string strtest = @"<relationships> <variationparent xmlns='http://www.microsoft.com/schema/products/2011-10-01'> <identifiers> <marketplaceasin> <marketplaceid>atvpdkikx0der</marketplaceid> <asin>b00k69wurq</asin> </marketplaceasin> <marketplaceasin> <marketplaceid>tbvpdkikx0der</marketplaceid> <asin>c00k69wurq</asin> </marketplaceasin> <marketplaceasin> <marketplaceid>klvpdkikx0der</marketplaceid> <asin>d00k69wurq</asin> </marketplaceasin> </identifiers> </variationparent> </relationships>"; textbox1.text = ""; xmldocument doc = new xmldocument(); doc.loadxml(strtest); xmlelement root = doc.documentelement; //用于带命名空间的xml操作 xmlnamespacemanager nsmgr = new xmlnamespacemanager(doc.nametable); nsmgr.addnamespace("ab", "http://www.microsoft.com/schema/products/2011-10-01"); xmlnodelist macthnodes = root.selectnodes("//ab:identifiers/ab:marketplaceasin", nsmgr); for (int i = 0; i < macthnodes.count; i++) { //删除生成的命名空间,生成标准xml。 string matchnode = cleanxmlnstag(macthnodes[i].outerxml); marketplaceasin ma = xmlutil.deserialize(typeof(marketplaceasin), matchnode) as marketplaceasin; if (ma != null) { response.write(ma.marketplaceid + "---------" + ma.asin + "<br/>"); } } } /* 实体对象 */ public class marketplaceasin { public string marketplaceid { set; get; } public string asin { set; get; } } protected string cleanxmlnstag(string xml) { xml = xml.replace("xmlns=\"http://www.microsoft.com/schema/products/2011-10-01\"", ""); return xml; }
以上就是用c#实现xml和实体类之间序列化和反序列化相互转换的详细内容。
其它类似信息

推荐信息