XML operations in C #

Source: Internet
Author: User

Serialized into a string:

 Public Static string Xmlserialize<t>(T entity)         {             new  StringBuilder ();                           New XmlSerializer (typeof(T));              using New StringWriter (buffer))             {                 serializer. Serialize (writer, entity);             }                         return buffer. ToString ();                      

Deserialization into an object:

     Public StaticT dexmlserialize<t> (stringxmlstring) {T Cloneobject=default(T); StringBuilder Buffer=NewStringBuilder (); Buffer.                        Append (xmlstring); XmlSerializer Serializer=NewXmlSerializer (typeof(T)); using(TextReader reader =NewStringReader (buffer. ToString ())) {Object obj=Serializer.                      Deserialize (reader); Cloneobject=(T) obj; }                        returnCloneobject; }  

Take the form of MemoryStream:

 public  static  string  xmlserialize<t> (T obj) { string  xmlstring = string   = new  XmlSerializer (typeof   (T));  using  (MemoryStream ms = new   MemoryStream ()) {xmlserializer.serialize (MS, obj); xmlstring  = Encoding.UTF8.GetString (Ms.          ToArray ());       return   xmlstring; }
   Public StaticT xmldeserialize<t> (stringxmlstring) {T T=default(T); XmlSerializer XmlSerializer=NewXmlSerializer (typeof(T)); using(Stream Xmlstream =NewMemoryStream (Encoding.UTF8.GetBytes (xmlstring))) {              using(XmlReader XmlReader =xmlreader.create (Xmlstream)) {Object obj=xmlserializer.deserialize (XmlReader); T=(T) obj; }          }          returnT; }  

Generate File:

 string  strfile = @ " c:/zero.xml   ;  using  (FileStream fs = new   FileStream (strfile, FileMode.Create)) {XmlSerializer Formatter  = new  XmlSerializer ( (T)); Formatter.            Serialize (FS, entity); }
NewNew New XmlSerializer (typeof (T)); formatter. Serialize (writer,entity);

XML operations in C #

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.