/// <summary> ///serialization and deserialization of XML/// </summary> Public classXmlutil { Public Static stringGetroot (stringxml) {XmlDocument doc=NewXmlDocument (); Doc. LOADXML (XML. Replace ("\ r \ n",""). Replace (" /",""). Trim ()); varE =Doc. DocumentElement; returnE.innertext; } #regionDeserialization/// <summary> ///deserialization/// </summary> /// <param name= "xml" >XML string</param> /// <returns></returns> Public StaticT deserialize<t> (stringXML) {returnT Deserialize (typeof(T), XML); } /// <summary> ///deserialization/// </summary> /// <param name= "Stream" >Byte stream</param> /// <returns></returns> Public StaticT deserialize<t>(Stream stream) {returnT Deserialize (typeof(T), stream); } /// <summary> ///deserialization/// </summary> /// <param name= "type" >type</param> /// <param name= "xml" >XML string</param> /// <returns></returns> Public Static ObjectDeserialize (type type,stringXML) {Try{XML= XML. Replace ("\ r \ n",""). Replace (" /",""). Trim (); using(StringReader sr =NewStringReader (XML)) {XmlSerializer Xmldes=NewXmlSerializer (type); returnXmldes. Deserialize (SR); } } Catch(Exception e) {return NULL; } } /// <summary> ///deserialization/// </summary> /// <param name= "type" ></param> /// <param name= "xml" ></param> /// <returns></returns> Public Static ObjectDeserialize (type type, stream stream) {XmlSerializer xmldes=NewXmlSerializer (type); returnXmldes. Deserialize (stream); } #endregion #regionSerialization of/// <summary> ///Serialization of/// </summary> /// <param name= "obj" >Object</param> /// <returns></returns> Public Static stringSerializer<t>(T obj) {returnSerializer (typeof(T), obj); } /// <summary> ///Serialization of/// </summary> /// <param name= "type" >type</param> /// <param name= "obj" >Object</param> /// <returns></returns> Public Static stringSerializer (Type type,Objectobj) {MemoryStream Stream=NewMemoryStream (); XmlSerializerNamespaces _name=Newxmlserializernamespaces (); _name. ADD ("","");//this removes the xmlns:xsi and xmlns:xsd inside the attribute.XmlWriterSettings xmlwritersettings =Newxmlwritersettings (); Xmlwritersettings.encoding=NewUTF8Encoding (false);//setting the encoding, not using ENCODING.UTF8, will result in BOM taggingXmlwritersettings.indent =true;//Set auto Indent//xmlwritersettings.omitxmldeclaration = true;//Delete xmldeclaration:<?xml version= "1.0" encoding= "utf-16"?>//xmlwritersettings.newlinechars = "\ r \ n"; //xmlwritersettings.newlinehandling = Newlinehandling.none;XmlSerializer XML =NewXmlSerializer (type); Try { using(XmlWriter XmlWriter =xmlwriter.create (Stream, xmlwritersettings)) { //Serializing ObjectsXML. Serialize (XmlWriter, obj, _name); } } Catch(InvalidOperationException) {Throw; } returnEncoding.UTF8.GetString (Stream.toarray ()). Trim (); } #endregion }
Serialization between entity classes and XML