C # Object serialization:
Public class xmlhelper {// <summary> // serialize the object to an XML string // </Summary> Public static string xmlserialize <t> (t obj) {string xmlstring = string. empty; xmlserializer = new xmlserializer (typeof (t); // using (textwriter = new streamwriter ("d :\\ xmltest. XML ") // {// xmlserializer. serialize (textwriter, OBJ); //} using (memorystream MS = new memorystream () {xmlserializer. serialize (MS, OBJ); xmlstring = encoding. utf8.getstring (Ms. toarray ();} return xmlstring ;} /// <summary> // XML string deserialization to object // </Summary> Public static t xmldeserialize <t> (string xmlstring) {T = default (t); xmlserializer = new xmlserializer (typeof (t); Using (Stream xmlstream = new memorystream (encoding. utf8.getbytes (xmlstring) {using (xmlreader = xmlreader. create (xmlstream) {object OBJ = xmlserializer. deserialize (xmlreader); t = (t) OBJ ;}} return t ;}}
Example:
[Serializable] [xmltype (typename = "mysong")] public class song {[xmlelement ("A")] Public String artist; [xmlelement ("S")] public String songtitle;} class xmldemo {static void main (string [] ARGs) {list <song> List = new list <song> () {New Song () {songtitle = "song title 1", artist = "singer 1"}, new song () {songtitle = "song title 2", artist = "singer 2 "}, new Song () {songtitle = "song title 3", artist = "singer 3" }}; string xmlstring = xmlhelper. XML Serialize (list);/* <? XML version = "1.0"?> <Arrayofsong xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema"> <song> <artist> artist 1 </artist> <songtitle> song title 1 </songtitle> </song> <artist> artist 2 </artist> <songtitle> song title 2 </songtitle> </song> <artist> artist 3 </artist> <songtitle> song title 3 </songtitle> </song> </arrayofsong> // custom tag name <? XML version = "1.0"?> <Arrayofmysong xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema"> <mysong> <A> artist 1 </a> <S> song title 1 </S> </mysong> <A> artist 2 </a> <S> song title 2 </S> </mysong> <A> artist 3 </a> <S> song title 3 </S> </mysong> </arrayofmysong> */console. writeline (xmlstring );}}
C # serialize an object to XML and customize the Tag Name