C#시리얼화반시리얼화

11334 단어
시리얼화된 객체
    public class People     {         [XmlAttribute("NAME")]         public string Name         { set; get; }         [XmlAttribute("AGE")]         public int Age         { set; get; }     }     [XmlRoot("Root")]     public class Student : People     {         [XmlElement("CLASS")]         public string Class         { set; get; }         [XmlElement("NUMBER")]         public int Number         { set; get; }     }
void Main(string[] args)
{
            Student stu = new Student()             {                 Age = 10,                 Class = "Class One",                 Name = "Tom",                 Number = 1             };             XmlSerializer ser = new XmlSerializer(typeof(Student));             ser.Serialize(File.Create("C:\\x.xml"), stu);
}
반서열화 대상
            XmlSerializer ser = new XmlSerializer(typeof(Student));             Student stu = ser.Deserialize(File.OpenRead("C:\\x.xml")) as Student;
객체 배열 서열화
    public class People     {         [XmlAttribute("NAME")]         public string Name         { set; get; }         [XmlAttribute("AGE")]         public int Age         { set; get; }     }     [XmlRoot("Root")]     public class Student : People     {         [XmlElement("CLASS")]         public string Class         { set; get; }         [XmlElement("NUMBER")]         public int Number         { set; get; }     }
void Main(string[] args)
{
            List stuList = new List();             stuList.Add(new Student() { Age = 10, Number = 1, Name = "Tom", Class = "Class One"});             stuList.Add(new Student() { Age = 11, Number = 2, Name = "Jay", Class = "Class Two"});             stuList.Add(new Student() { Age = 12, Number = 3, Name = "Pet", Class = "Class One"});             stuList.Add(new Student() { Age = 13, Number = 4, Name = "May", Class = "Class Three"});             stuList.Add(new Student() { Age = 14, Number = 5, Name = "Soy", Class = "Class Two"});             XmlSerializer ser = new XmlSerializer(typeof(List));             ser.Serialize(File.Create("C:\\x.xml"), stuList);
}
객체 배열 반전
            XmlSerializer ser = new XmlSerializer(typeof(List));             List stuList = ser.Deserialize(File.OpenRead("C:\\x.xml")) as List;             foreach (Student s in stuList)             {                 MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",                     s.Name, s.Age, s.Class, s.Number));             }
Dirctionary 시리얼화
    public struct DirectionList     {         [XmlAttribute("Name")]         public string Name;         [XmlElement("Value")]         public int Value;     }
void Main(string[] args)
{
            Dictionary list = new Dictionary();             list.Add("1", 100);             list.Add("2", 200);             list.Add("3", 300);             list.Add("4", 400);             list.Add("5", 500);             list.Add("6", 600);             list.Add("7", 700);             list.Add("8", 800);             list.Add("9", 900);
            List dirList = new List();             foreach (var s in list)             {                 dirList.Add(new DirectionList() { Name = s.Key, Value = s.Value });             }             XmlSerializer ser = new XmlSerializer(typeof(List));             ser.Serialize(File.Create("C:\\x.xml"), dirList);
}
여기서 한 가지 더 말하자면 XmlSerializer에서Dirctionary<> 유형의 대상은 지원되지 않기 때문에 이런 가장 흔히 볼 수 있는 유형을 서열화할 때 그 형식에 따라 다른 서열화할 수 있는 유형을 만들 수 밖에 없다. 여기서 나는 구조체를 정의했다. 물론 너도 다른 종류로 정의할 수 있다.Dictionary<>의 데이터를 구조체에 순서대로 넣으면 흐름에 넣을 수 있습니다.
[XmlAttribute("Name")] 이 필드를 xml의 속성으로 하고 속성 이름을 ""에 따른다는 뜻입니다.
[XmlElement("Value")] 이 필드를 xml 요소로 만듭니다.
Dirctionary 역정렬
            XmlSerializer ser = new XmlSerializer(typeof(List));             List dirList = ser.Deserialize(                 File.OpenRead("C:\\x.xml")) as List;             foreach (var v in dirList)             {                 Console.WriteLine("{0} : {1}", v.Name, v.Value);             }
사실 나는 이 명칭을 좋아하지 않는다. 약간 생화학 위기의 feel을 느낀다. 그러나 그렇다. 너무 자랑스러운 부분이 없다. Deserialize는 반서열화된다.희망적이군.Net에서Dirctionary<> 대상을 통합할 수 있다면 게으른 사람들이 편리할 것입니다.
서열화가 필요한 대열에서, 수조는 매우 흔히 볼 수 있는 유형이고, 그 다음은 그림이다
서열화 그림
    public struct ImageStruct     {         [XmlAttribute("Number")]         public int number;         [XmlElement("Image")]         public byte[] picture;     }
void Main(string[] args)
{
            ImageStruct s = new ImageStruct() { number = 1, picture = File.ReadAllBytes(@"11.jpg") };             XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));             FileStream fs = File.Create("c:\\x.xml");             ser.Serialize(fs, s);             fs.Close();
}
마찬가지로 구조체로 그림을 보존하는데 여기에 그림의 이름도 붙여서 찾아보기에도 편리하다
그림 반서열화
            XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));             ImageStruct s = (ImageStruct)ser.Deserialize(File.OpenRead("c:\\x.xml"));             pictureBox1.Image = Image.FromStream(new MemoryStream(s.picture));
겉치레가 없는 방식으로memorystream을 이용하여 캐시를 하면 비교적 빠를 것이다. 사실 나는 별로 느끼지 않는다.
그림 배열화
    public struct ImageStruct     {         [XmlAttribute("Number")]         public int number;         [XmlElement("Image")]         public byte[] picture;     }
void Main(string[] args)
{
            List imageList = new List();             imageList.Add(new ImageStruct()             {                 number = 1,                 picture = File.ReadAllBytes(@"11.jpg")             });             imageList.Add(new ImageStruct()             {                 number = 2,                 picture = File.ReadAllBytes(@"22.jpg")             });
            XmlSerializer ser = new XmlSerializer(typeof(List));             FileStream fs = File.Create("c:\\x.xml");             ser.Serialize(fs, imageList);             fs.Close();
}
그림 배열 반서열화
            XmlSerializer ser = new XmlSerializer(typeof(List));             List s = (List)ser.Deserialize(File.OpenRead("c:\\x.xml"));             var im = from i in s                      where i.number == 1                      select i.picture;
           //var im = s.Where(p => p.number == 1).Select(p => p.picture);             foreach (var image in im)             {                 pictureBox1.Image = Image.FromStream(                     new MemoryStream(image));             }
여기에 수조 구조에 대해 Linq 조회를 진행하였는데, 이렇게 하면 매우 편리하게 그림을 조회할 수 있다
 
  public class People
    {
        [XmlAttribute("NAME")]
        public string Name
        { set; get; }
        [XmlAttribute("AGE")]
        public int Age
        { set; get; }
    }
    [XmlRoot("Root")]
    public class Student : People
    {
        [XmlElement("CLASS")]
        public string Class
        { set; get; }
        [XmlElement("NUMBER")]
        public int Number
        { set; get; }
    }

    public class People1
    {
        [XmlAttribute("Type")]
        public string type
        { set; get; }
        [XmlAttribute("ISBN")]
        public string isbn
        { set; get; }
    }
    [XmlRoot("Root")]
    public class Student2 : People1
    {
        [XmlElement("title")]
        public string title
        { set; get; }
        [XmlElement("author")]
        public string author
        { set; get; }
        [XmlElement("price")]
        public float price
        { set; get; }
    }
    //----------------------------------------------//
    // 
    //1、 xml    Student2  xml  ArrayOfStudent2  root Student2
    //2、  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    //---------------------------------------------//
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            XmlDeSerializerFun2();
        }

        private void XmlSerializerFun()
        {
            List<Student> stuList = new List<Student>();
            stuList.Add(new Student() { Age = 10, Number = 1, Name = "Tom", Class = "Class One" });
            stuList.Add(new Student() { Age = 11, Number = 2, Name = "Jay", Class = "Class Two" });
            stuList.Add(new Student() { Age = 12, Number = 3, Name = "Pet", Class = "Class One" });
            stuList.Add(new Student() { Age = 13, Number = 4, Name = "May", Class = "Class Three" });
            stuList.Add(new Student() { Age = 14, Number = 5, Name = "Soy", Class = "Class Two" });
            XmlSerializer ser = new XmlSerializer(typeof(List<Student>));
            ser.Serialize(File.Create("C:\\x.xml"), stuList);
        }
        private void XmlDeSerializerFun()
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Student>));
            List<Student> stuList = ser.Deserialize(File.OpenRead("C:\\x.xml")) as List<Student>;
            foreach (Student s in stuList)
            {
                MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",
                    s.Name, s.Age, s.Class, s.Number));
            }
        }
        
        private void XmlDeSerializerFun2()
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Student2>));
            List<Student2> stuList = ser.Deserialize(File.OpenRead("C:\\XMLtest.xml")) as List<Student2>;
            foreach (Student2 s in stuList)
            {
                MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",
                    s.type,s.isbn,s.title,s.author,s.price));
            }
        }
    }

좋은 웹페이지 즐겨찾기