C # XML serialization and de-serialization

The main two ways 1.BinaryFormatter 2.XmlSerializer

Create Object

[The Serializable] // if it is saved in a class field, you must add this attribute (C # inside enclosed in brackets identifier) in front of the class 
public  class the Person
{
    public int age;

    public string name;

    [NonSerialized] // If a field is do not want to be saved, then add such a sign

    public string secret;

}

1.BinaryFormatter (good performance)

class Program
{
    static void Main(string[] args)
    {
       // sequence of 
        the Person Person = new new the Person ();
        person.age = 18;
        person.name = "tom";
        person.secret = "i will not tell you";
        FileStream stream = new FileStream(@"c:\temp\person.dat", FileMode.Create);
BinaryFormatter bFormat
= newBinaryFormatter(); bFormat.Serialize(stream, person); stream.Close(); // deserialize the Person Person = new new the Person (); FileStream stream = new FileStream(@"c:\temp\person.dat", FileMode.Open);
BinaryFormatter bFormat
= new BinaryFormatter(); Person = (the Person) bFormat.Deserialize (Stream); // deserialization of an object is obtained by the object must be cast. stream.Close (); Console.WriteLine (person.age + + PERSON.NAME person.secret); // result 18tom secret because there is no serialization. } }

2.XmlSerializer (common)

// sequence of 
the Person Person = new new the Person ();
person.age = 18;
person.name = "tom";
person.secret = "i will not tell you";
FileStream stream = new FileStream(@"c:\temp\xmlFormat.xml", FileMode.Create);

XmlSerializer xmlserilize = new XmlSerializer(typeof(Person));
xmlserilize.Serialize(stream, person);
stream.Close();

// deserialize 
the Person Person = new new the Person ();
FileStream stream =new FileStrea (@"c:\temp\xmlFormat.xml",FileMode.Open);

XmlSerializerxmlserilize = new XmlSerializer(typeof(Person));
person = (Person)xmlserilize.Deserialize(stream);
stream.Close();

Console.WriteLine(person.age + person.name + person.secret);

general idea:

Serialization:

  1. obtain a stored object type

  2. Create a written document flow

  3. To define the sequence of the type

  4. Method calling sequence

Deserialization:

  1. Define a type of load object

  2. Create a file stream read

  3. To define the type deserialize

  4. The method of call deserialization

 

Guess you like

Origin www.cnblogs.com/zhang1f/p/11093520.html