C#实现Xml序列化与反序列化的方法
本文实例讲述了C#实现Xml序列化与反序列化的方法。分享给大家供大家参考。具体实现方法如下:
///<summary> ///Xml序列化与反序列化 ///</summary> publicclassXmlUtil { publicstaticstringGetRoot(stringxml) { XmlDocumentdoc=newXmlDocument(); doc.LoadXml(xml.Replace("\r\n","").Replace("\0","").Trim()); vare=doc.DocumentElement; returne.InnerText; }
#region反序列化 ///<summary> ///反序列化 ///</summary> ///<paramname="xml">XML字符串</param> ///<returns></returns> publicstaticTDeserialize<T>(stringxml) { return(T)Deserialize(typeof(T),xml); } ///<summary> ///反序列化 ///</summary> ///<paramname="stream">字节流</param> ///<returns></returns> publicstaticTDeserialize<T>(Streamstream) { return(T)Deserialize(typeof(T),stream); } ///<summary> ///反序列化 ///</summary> ///<paramname="type">类型</param> ///<paramname="xml">XML字符串</param> ///<returns></returns> publicstaticobjectDeserialize(Typetype,stringxml) { try { xml=xml.Replace("\r\n","").Replace("\0","").Trim(); using(StringReadersr=newStringReader(xml)) { XmlSerializerxmldes=newXmlSerializer(type); returnxmldes.Deserialize(sr); } } catch(Exceptione) { returnnull; } } ///<summary> ///反序列化 ///</summary> ///<paramname="type"></param> ///<paramname="xml"></param> ///<returns></returns> publicstaticobjectDeserialize(Typetype,Streamstream) { XmlSerializerxmldes=newXmlSerializer(type); returnxmldes.Deserialize(stream); } #endregion #region序列化 ///<summary> ///序列化 ///</summary> ///<paramname="obj">对象</param> ///<returns></returns> publicstaticstringSerializer<T>(Tobj) { returnSerializer(typeof(T),obj); } ///<summary> ///序列化 ///</summary> ///<paramname="type">类型</param> ///<paramname="obj">对象</param> ///<returns></returns> publicstaticstringSerializer(Typetype,objectobj) { MemoryStreamStream=newMemoryStream(); XmlSerializerNamespaces_name=newXmlSerializerNamespaces(); _name.Add("","");//这样就去掉attribute里面的xmlns:xsi和xmlns:xsd XmlWriterSettingsxmlWriterSettings=newXmlWriterSettings(); xmlWriterSettings.Encoding=newUTF8Encoding(false);//设置编码,不能用Encoding.UTF8,会导致带有BOM标记 xmlWriterSettings.Indent=true;//设置自动缩进 //xmlWriterSettings.OmitXmlDeclaration=true;//删除XmlDeclaration:<?xmlversion="1.0"encoding="utf-16"?> //xmlWriterSettings.NewLineChars="\r\n"; //xmlWriterSettings.NewLineHandling=NewLineHandling.None; XmlSerializerxml=newXmlSerializer(type); try { using(XmlWriterxmlWriter=XmlWriter.Create(Stream,xmlWriterSettings)) { //序列化对象 xml.Serialize(xmlWriter,obj,_name); } } catch(InvalidOperationException) { throw; } returnEncoding.UTF8.GetString(Stream.ToArray()).Trim(); } #endregion }