C # serialize and deserialize objects in XML format

Source: Internet
Author: User

Class of the object to be serialized:

[Serializable]
Public class person
{
Private string name;
Public string name
{
Get
{
Return name;
}
Set
{
Name = value;
}
}
Public String sex;
Public int age = 31;
Public Course [] courses;

Public Person ()
{
}
Public Person (string name)
{
Name = Name;
Sex = 'male ';
}
}
[Serializable]
Public class course
{
Public string name;
[Xmlignore] Public String description;
Public Course ()
{
}
Public Course (string name, string description)
{
Name = Name;
Description = description;
}
}

Test classes for serialization and deserialization:

Class Test
{
// Serialization
Public void serialiaze ()
{
Person c = new person ('cyj ')
C. Courses = new course [2];
C. Courses [0] = New Course ('English ', 'communication tools ')
C. Courses [1] = New Course ('mat', 'natural scientifically ')

xmlserializer xs = new xmlserializer (typeof (person);
stream = new filestream ('C: \ CYJ. xml', filemode. create, fileaccess. write, fileshare. readwrite);
Xs. serialize (stream, c);
stream. close ();
}< br> // deserialization
Public void deserialize ()
{< br> xmlserializer xs = new xmlserializer (typeof (person);
stream = new filestream ('C: \ CYJ. xml', filemode. open, fileaccess. read, fileshare. readwrite);
person P = (person) XS. deserialize (Stream);
console. writeline (P. name);
console. writeline (P. age. tostring ();
console. writeline (P. courses. length. tostring ();
console. read ();
}< BR >}

the formatted XML document content is:


male
31


English

mathematics


CYJ

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.