C # Object XML serialization two implementation code

Source: Internet
Author: User
Tags soap object serialization serialization

using System;
Using System.Xml;
Using System.Xml.Serialization;
Using System.Text;
Using System.IO;
public class Util
{
<summary>
object is serialized into an XML string
</summary>
public static string xmlserialize<t> (T obj)
{
string xmlstring = String.Empty;
XmlSerializer xmlserializer = new XmlSerializer (typeof (T));
using (MemoryStream ms = new MemoryStream ())
{
Xmlserializer.serialize (MS, obj);
xmlstring = encoding.utf8.getstring (Ms.toarray ());
}
return xmlstring;
}

<summary>
XML string deserialized into an object
</summary>
public static T Xmldeserialize<t> (String xmlstring)
{
T t = default (t);
XmlSerializer xmlserializer = new XmlSerializer (typeof (T));
using (Stream xmlstream = new MemoryStream (encoding.utf8.getbytes (xmlstring))
{
Using (XmlReader XmlReader = Xmlreader.create (Xmlstream))
{
Object obj = Xmlserializer.deserialize (XmlReader);
t = (t) obj;
}
}
return t;
}
}

Stringwriter,xmlserializer the object, the collection of objects into an XML-formatted string, and describes how to deserialize it.


C # serialization Xmlserializer,binaryformatter,soapformatter

Radio.cs
using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Simpleserialize
{
[Serializable]
public class Radio
{
public bool Hastweeters;
public bool Hassubwoofers;
Public double[] Stationpresets;

[NonSerialized]
public string radioid = "XF-552RR6";
}
}

Cars.cs
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Xml.Serialization;

Namespace Simpleserialize
{
[Serializable]
public class car
{
Public Radio Theradio = new Radio ();
public bool Ishatchback;
}

[Serializable, XmlRoot (namespace = "http://www.intertech.com")]
public class Jamesbondcar:car
{
[XmlAttribute]
public bool Canfly;
[XmlAttribute]
public bool Cansubmerge;

Public Jamesbondcar (bool skyworthy, BOOL seaworthy)
{
Canfly = Skyworthy;
Cansubmerge = seaworthy;
}
The XmlSerializer demands a default constructor!
Public Jamesbondcar () {}
}
}


Program.cs
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;

For the formatters.
Using System.Runtime.Serialization.Formatters.Binary;
Using System.Runtime.Serialization.Formatters.Soap;
Using System.Xml.Serialization;

Namespace Simpleserialize
{
Class Program
{
static void Main (string[] args)
{
Console.WriteLine ("* * Fun with Object serialization *****n");

Make a jamesbondcar and set state.
Jamesbondcar JBC = new Jamesbondcar ();
Jbc.canfly = true;
Jbc.cansubmerge = false;
Jbc.theradio.stationpresets = new double[] {89.3, 105.1, 97.1};
Jbc.theradio.hastweeters = true;

Now save/load the "car" to a specific file.
Saveasbinaryformat (JBC, "Cardata.dat");
Loadfrombinaryfile ("Cardata.dat");
Saveassoapformat (JBC, "Cardata.soap");
Saveasxmlformat (JBC, "cardata.xml");
Savelistofcars ();
Savelistofcarsasbinary ();

Console.ReadLine ();
}

#region save/load as binary format
static void Saveasbinaryformat (object objgraph, string filename)
{
Save object to a file named Cardata.dat in binary.
BinaryFormatter Binformat = new BinaryFormatter ();

using (Stream fstream = new FileStream (filename,
FileMode.Create, FileAccess.Write, Fileshare.none))
{
Binformat.serialize (FStream, objgraph);
}
Console.WriteLine ("=> saved car in binary format!");
}

static void Loadfrombinaryfile (string filename)
{
BinaryFormatter Binformat = new BinaryFormatter ();

Read the Jamesbondcar from the binary file.
using (Stream fstream = file.openread (filename))
{
Jamesbondcar Carfromdisk =
(Jamesbondcar) binformat.deserialize (fstream);
Console.WriteLine ("Can this car fly: {0}", carfromdisk.canfly);
}
}
#endregion

    #region Save as SOAP format
   //Is sure to import system.runtime.serialization . FORMATTERS.SOAP
   //and reference System.runtime.serialization.formatters.soap.dll.
    static void Saveassoapformat (object objgraph, string filename)
    {
 & nbsp;   //Save object to a file named Cardata.soap in SOAP format.
      SoapFormatter soapformat = new SoapFormatter ();

using (Stream fstream = new FileStream (filename,
FileMode.Create, FileAccess.Write, Fileshare.none))
{
Soapformat.serialize (FStream, objgraph);
}
Console.WriteLine ("=> saved car in soap format!");
}
#endregion

#region Save as XML format
static void Saveasxmlformat (object objgraph, string filename)
{
Save object to a file named Cardata.xml in XML format.
XmlSerializer Xmlformat = new XmlSerializer (typeof (Jamesbondcar),
New type[] {typeof (radio), typeof (Car)});

      using (Stream fstream = new FileStream (filename,
         FileMode.Create, FileAccess.Write, Fileshare.none))
      {
         xmlformat.serialize (FStream, objgraph);
     }
      Console.WriteLine ("=> saved car in XML format!");
   }
    #endregion

    #region Save collection of cars
    static void Savelistofcars ()
 & nbsp;  {
     //Now persist a list<> of jamesbondcars.
   & nbsp;  list<jamesbondcar> mycars = new list<jamesbondcar> ();
      Mycars.add (New Jamesbondcar (True, true));
      Mycars.add (New Jamesbondcar (True, false));
      Mycars.add (new Jamesbondcar (False, true));
      Mycars.add (False, False) (new Jamesbondcar);

using (Stream fstream = new FileStream ("Carcollection.xml"),
FileMode.Create, FileAccess.Write, Fileshare.none))
{
XmlSerializer Xmlformat = new XmlSerializer (typeof (List<jamesbondcar>),
New type[] {typeof (Jamesbondcar), typeof (Car), typeof (Radio)});
Xmlformat.serialize (FStream, mycars);
}
Console.WriteLine ("=> saved list of cars!");
}

static void Savelistofcarsasbinary ()
{
Save ArrayList Object (Mycars) as binary.
list<jamesbondcar> mycars = new list<jamesbondcar> ();

      BinaryFormatter Binformat = new BinaryFormatter ();
      using (Stream fstream = new FileStream ("Allmycars.dat",
         FileMode.Create, FileAccess.Write, Fileshare.none))
      {
        binformat.serialize (FStream, mycars);
     }
      Console.WriteLine ("=> saved list of cars in binary!");
   }
    #endregion
 }
}

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.