C # XML and objects convert to each other

Source: Internet
Author: User

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Text;4 usingSystem.Xml.Serialization;5 usingSystem.IO;6 usingSystem.Xml;7 8 namespaceCommon9 {Ten      Public classxmlutility One     { A         /// <summary> -         ///serializing a custom object to an XML string -         /// </summary> the         /// <param name= "MyObject" >Custom Object Entities</param> -         /// <returns>Serialized XML string</returns> -          Public Static stringSerializetoxml<t>(T myObject) -         { +             if(MyObject! =NULL) -             { +XmlSerializer xs =NewXmlSerializer (typeof(T)); A  atMemoryStream stream =NewMemoryStream (); -XmlTextWriter writer =NewXmlTextWriter (Stream, Encoding.UTF8); -Writer. formatting = Formatting.none;//Indent in - XS. Serialize (writer, myObject); -  -Stream. Position =0; inStringBuilder SB =NewStringBuilder (); -                 using(StreamReader reader =NewStreamReader (Stream, Encoding.UTF8)) to                 { +                     stringLine ; -                      while(line = reader.) ReadLine ())! =NULL) the                     { * sb. Append (line); $                     }Panax Notoginseng Reader. Close (); -                 } the writer. Close (); +                 returnsb. ToString (); A             } the             return string. Empty; +         } -  $         /// <summary> $         ///deserializing an XML string into an object -         /// </summary> -         /// <typeparam name= "T" >Object Type</typeparam> the         /// <param name= "xml" >XML Characters</param> -         /// <returns></returns>Wuyi          Public StaticT deserializetoobject<t> (stringXML) the         { - T MyObject; WuXmlSerializer serializer =NewXmlSerializer (typeof(T)); -StringReader reader =NewStringReader (XML); AboutMyObject =(T) serializer. Deserialize (reader); $ Reader. Close (); -             returnMyObject; -         } -     } A}

C # XML and objects convert to each other

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.