C#实现对象XML序列化的方法
本文实例讲述了C#实现对象XML序列化的方法。分享给大家供大家参考。具体实现方法如下:
usingsystem; usingsystem.xml; usingsystem.xml.serialization; usingsystem.text; usingsystem.io; publicclassutil { ///<summary> ///对象序列化成xmlstring ///</summary> publicstaticstringxmlserialize<t>(tobj) { stringxmlstring=string.empty; xmlserializerxmlserializer=newxmlserializer(typeof(t)); using(memorystreamms=newmemorystream()) { xmlserializer.serialize(ms,obj); xmlstring=encoding.utf8.getstring(ms.toarray()); } returnxmlstring; } ///<summary> ///xmlstring反序列化成对象 ///</summary> publicstatictxmldeserialize<t>(stringxmlstring) { tt=default(t); xmlserializerxmlserializer=newxmlserializer(typeof(t)); using(streamxmlstream=newmemorystream(encoding.utf8.getbytes(xmlstring))) { using(xmlreaderxmlreader=xmlreader.create(xmlstream)) { objectobj=xmlserializer.deserialize(xmlreader); t=(t)obj; } } returnt; } }
stringwriter,xmlserializer将对象、对象集合序列化为xml格式的字符串,同时描述如何进行反序列化.
c#序列化xmlserializer,binaryformatter,soapformatter
//radio.cs usingsystem; usingsystem.collections.generic; usingsystem.text; namespacesimpleserialize { [serializable] publicclassradio { publicboolhastweeters; publicboolhassubwoofers; publicdouble[]stationpresets; [nonserialized] publicstringradioid="xf-552rr6"; } } //cars.cs usingsystem; usingsystem.collections.generic; usingsystem.text; usingsystem.xml.serialization; namespacesimpleserialize { [serializable] publicclasscar { publicradiotheradio=newradio(); publicboolishatchback; } [serializable,xmlroot(namespace="http://www.intertech.com")] publicclassjamesbondcar:car { [xmlattribute] publicboolcanfly; [xmlattribute] publicboolcansubmerge; publicjamesbondcar(boolskyworthy,boolseaworthy) { canfly=skyworthy; cansubmerge=seaworthy; } //thexmlserializerdemandsadefaultconstructor! publicjamesbondcar(){} } }
//program.cs usingsystem; usingsystem.collections.generic; usingsystem.text; usingsystem.io; //fortheformatters. usingsystem.runtime.serialization.formatters.binary; usingsystem.runtime.serialization.formatters.soap; usingsystem.xml.serialization; namespacesimpleserialize { classprogram { staticvoidmain(string[]args) { console.writeline("*****funwithobjectserialization*****n"); //makeajamesbondcarandsetstate. jamesbondcarjbc=newjamesbondcar(); jbc.canfly=true; jbc.cansubmerge=false; jbc.theradio.stationpresets=newdouble[]{89.3,105.1,97.1}; jbc.theradio.hastweeters=true; //nowsave/loadthecartoaspecificfile. saveasbinaryformat(jbc,"cardata.dat"); loadfrombinaryfile("cardata.dat"); saveassoapformat(jbc,"cardata.soap"); saveasxmlformat(jbc,"cardata.xml"); savelistofcars(); savelistofcarsasbinary(); console.readline(); } #regionsave/loadasbinaryformat staticvoidsaveasbinaryformat(objectobjgraph,stringfilename) { //saveobjecttoafilenamedcardata.datinbinary. binaryformatterbinformat=newbinaryformatter(); using(streamfstream=newfilestream(filename, filemode.create,fileaccess.write,fileshare.none)) { binformat.serialize(fstream,objgraph); } console.writeline("=>savedcarinbinaryformat!"); } staticvoidloadfrombinaryfile(stringfilename) { binaryformatterbinformat=newbinaryformatter(); //readthejamesbondcarfromthebinaryfile. using(streamfstream=file.openread(filename)) { jamesbondcarcarfromdisk= (jamesbondcar)binformat.deserialize(fstream); console.writeline("canthiscarfly?:{0}",carfromdisk.canfly); } } #endregion #regionsaveassoapformat //besuretoimportsystem.runtime.serialization.formatters.soap //andreferencesystem.runtime.serialization.formatters.soap.dll. staticvoidsaveassoapformat(objectobjgraph,stringfilename) { //saveobjecttoafilenamedcardata.soapinsoapformat. soapformattersoapformat=newsoapformatter(); using(streamfstream=newfilestream(filename, filemode.create,fileaccess.write,fileshare.none)) { soapformat.serialize(fstream,objgraph); } console.writeline("=>savedcarinsoapformat!"); } #endregion #regionsaveasxmlformat staticvoidsaveasxmlformat(objectobjgraph,stringfilename) { //saveobjecttoafilenamedcardata.xmlinxmlformat. xmlserializerxmlformat=newxmlserializer(typeof(jamesbondcar), newtype[]{typeof(radio),typeof(car)}); using(streamfstream=newfilestream(filename, filemode.create,fileaccess.write,fileshare.none)) { xmlformat.serialize(fstream,objgraph); } console.writeline("=>savedcarinxmlformat!"); } #endregion #regionsavecollectionofcars staticvoidsavelistofcars() { //nowpersistalist<>ofjamesbondcars. list<jamesbondcar>mycars=newlist<jamesbondcar>(); mycars.add(newjamesbondcar(true,true)); mycars.add(newjamesbondcar(true,false)); mycars.add(newjamesbondcar(false,true)); mycars.add(newjamesbondcar(false,false)); using(streamfstream=newfilestream("carcollection.xml", filemode.create,fileaccess.write,fileshare.none)) { xmlserializerxmlformat=newxmlserializer(typeof(list<jamesbondcar>), newtype[]{typeof(jamesbondcar),typeof(car),typeof(radio)}); xmlformat.serialize(fstream,mycars); } console.writeline("=>savedlistofcars!"); } staticvoidsavelistofcarsasbinary() { //savearraylistobject(mycars)asbinary. list<jamesbondcar>mycars=newlist<jamesbondcar>(); binaryformatterbinformat=newbinaryformatter(); using(streamfstream=newfilestream("allmycars.dat", filemode.create,fileaccess.write,fileshare.none)) { binformat.serialize(fstream,mycars); } console.writeline("=>savedlistofcarsinbinary!"); } #endregion } }
希望本文所述对大家的C#程序设计有所帮助。