C Note: object serialization and XML file

Keywords: xml Windows Database Attribute

(1) Object serialization and deserialization

1) Insufficient text saving objects

  • When the attributes of an object change, the number of information writes or reads needs to be increased or decreased;
  • Poor information security;

2) New method of object saving:

Use serialization and deserialization to save and restore objects; phase objects as a whole are saved once and then restored once;

Note: the collection object can also be saved; try to use serialization and deserialization for file saving, of course, it is also possible to use text files directly for general small files;

3) Specific operation of serialization:

Error:

If the following errors are encountered, the object can be serialized first. Usually, the object to be serialized is marked with [Serializable] before the object to be serialized

Serialization code:

After serialization, it becomes object type, so after deserialization, it is object type, which needs to be cast;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

//Bring in namespace
using System.IO;
//Introduce specific namespace: binary formatter
using System.Runtime.Serialization.Formatters.Binary;

namespace TextFile
{
    public partial class FrmFile : Form
    {
        public FrmFile()
        {
            InitializeComponent();
        }
        private void btnSerialize_Click(object sender, EventArgs e)
        {
            //Encapsulate object information
            Student objStu = new Student()
            {
                Name = this.txtName.Text.Trim(),
                Age = Convert.ToInt16(this.txtAge.Text.Trim()),
                Gender = this.txtGender.Text.Trim(),
                Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim())
            };
            //[1] Create a file stream
            FileStream fs = new FileStream("D:\\myFile\\objStudent.stu", FileMode.Create);
            //[2] Create a binary formatter
            BinaryFormatter formatter = new BinaryFormatter();
            //[3] Call serialization method
            formatter.Serialize(fs, objStu);
            //[4] Close file stream
            fs.Close();
        }
    }
}

Deserialization Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

//Bring in namespace
using System.IO;
//Introduce specific namespace: binary formatter
using System.Runtime.Serialization.Formatters.Binary;

namespace TextFile
{
    public partial class FrmFile : Form
    {
        public FrmFile()
        {
            InitializeComponent();
        }
        private void btnDeserialize_Click(object sender, EventArgs e)
        {
            //[1] Create a file stream
            FileStream fs = new FileStream("D:\\myFile\\objStudent.stu", FileMode.Open);
            //[2] Create a binary formatter
            BinaryFormatter formatter = new BinaryFormatter();
            //[3] Call the deserialization method and change to object type after serialization
            Student objStudent = (Student)formatter.Deserialize(fs); //The object type exists after deserialization, so type conversion should be enforced
            //[4] Close file stream
            fs.Close();

            //Display data
            this.txtName.Text = objStudent.Name;
            this.txtAge.Text = objStudent.Age.ToString();
            this.txtGender.Text = objStudent.Gender;
            this.txtBirthday.Text = objStudent.Birthday.ToShortDateString();
        }
    }
}

4) Application of serialization and deserialization

Application:
  • Application system configuration information (if the amount of information is large, the method is more convenient to read and write);
  • When the database is not needed, it can be used as the carrier of data access;
  • Delivery of WebService in Dixiang;
  • Data transfer between modules;
Benefits of serializing and deserializing objects:
  • The object is easy to save and read, and has strong expansibility;
  • Data security and efficiency;

(2) XML file operations

1) Introduction to XML

  • XML is the abbreviation of eXtensible Markup Language, which can be extended;
  • It is a kind of markup language that can be used to create custom, which is created by the World Wide Web Association (W3C) to overcome the limitations of HTML;
  • In terms of function, XML is mainly used for data storage, while HTML is mainly used for data display;

2) The format and syntax requirements of XML documents

Format requirements:
  • Determined and unique root element;
  • Start tag and end tag match;
  • Correct nesting of element labels;
  • Attribute values should be enclosed in quotation marks;
  • The attributes of the same element cannot be repeated;
Grammar requirements:
  • Element: < label > text content < / label >
  • Processing instruction: < XML version = "1.0"? >
  • Notes:
  • Properties: < salary current = "" US $> 25000 < / salary > [remove / preceding space]

3) application

  • Cross platform data interaction, typical application is the use of web service;
  • The common web service is train schedule;

4) XML file read

  • XML file data containing student information and data reading; steps:
    • Create document objects;
    • Load XML document;
    • Get the root node;
    • Traverse the nodes and encapsulate the data;
Implementation code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Xml;//Bring in namespace

namespace XMLDemo
{
    public partial class FrmReadXML : Form
    {
        public FrmReadXML()
        {
            InitializeComponent();
        }
        private void btnLoadXML_Click(object sender, EventArgs e)
        {
            XmlDocument objDoc = new XmlDocument();  //[1] Create XML document action object
            objDoc.Load("StuScore.xml");  //[2] Load XML file into document object
            XmlNode rootNode = objDoc.DocumentElement;  //[3] Get XML document root
            List<Student> list = new List<Student>();//Create an object collection         
            foreach (XmlNode stuNode in rootNode.ChildNodes)  //[4] Traverse the root node (the root node contains all nodes)
            {
                if (stuNode.Name == "Student")
                {
                    Student objStu = new Student();
                    foreach (XmlNode subNode in stuNode)  //[5] Traverse child nodes
                    {
                        switch (subNode.Name)//Encapsulate attributes to an object based on the name of the child node
                        {
                            case "StuName":
                                objStu.StuName = subNode.InnerText;//Get the node value corresponding to node name
                                break;
                            case "StuAge":
                                objStu.StuAge = Convert.ToInt16(subNode.InnerText);
                                break;
                            case "Gender":
                                objStu.Gender = subNode.InnerText;
                                break;
                            case "ClassName":
                                objStu.ClassName = subNode.InnerText;
                                break;
                        }
                    }
                    list.Add(objStu);
                }
            }
            //Display data in DataGridView
            this.dgvStuList.DataSource = list;
        }
        //display version information
        private void btnShowVersion_Click(object sender, EventArgs e)
        {
            //Create XML reader
            XmlTextReader tReader = new XmlTextReader("StuScore.xml");

            string info = string.Empty;

            //Cyclic query
            while (tReader.Read())
            {
                if (tReader.Name == "Version")
                {
                    info = "Edition:" + tReader.GetAttribute("vNo") + " Published:" 
                        + tReader.GetAttribute("pTime");
                    break;
                }
            }
            MessageBox.Show(info,"Data version");
        }
    }
}
Be careful:
  • When displaying data in a DataGridView, the name of the DataGridView and the DataPropertyName should be the same. The name of the latter is actually the name of the property in the class, and they can only be displayed if they are the same;

5) XML file reading summary

Common objects:
  • XML document object represents the whole XML document;
  • The XmlNode object represents a single node of the XML file;
Common properties and descriptions:

6) Find a specific node from the XML file

The method of traversal is very cumbersome and inefficient;
Search method can be used;

Published 37 original articles, won praise 1, visited 1031
Private letter follow

Posted by somedude on Tue, 28 Jan 2020 20:12:03 -0800