Received xml:

<?xml version="1.0"?> <ArrayOfIndividualNum xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <IndividualNum /> </ArrayOfIndividualNum> 

Main class code:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kursach { [Serializable] public class Investor { protected string name; protected string gender; protected string address; protected string birthday; public void setName(string yourName) { name = yourName; } public void setGender(string yourGender) { gender = yourGender; } public void setAddress(string yourAddress) { address = yourAddress; } public void setBirthday(string yourBirthday) { birthday = yourBirthday; } public string putName() { return name; } public string putGender() { return gender; } public string putAddress() { return address; } public string putBirthday() { return birthday; } // Конструктор без параметров public Investor() { name = ""; gender = ""; address = ""; birthday = ""; } public Investor(string one) { name = "one"; gender = ""; address = ""; birthday = ""; } } } 

Heir code:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace kursach { [Serializable] public class IndividualNum : Investor { private int numInvest; private int start; private string date; public void setNumInvest(int yourInvest) { numInvest = yourInvest; } public void setStart(int yourStart) { start = yourStart; } public void setDate(string yourDate) { date = yourDate; } public int getNumInvest() { return numInvest; } public int getStart() { return start; } public string getDate() { return date; } // Конструктор без параметров. public IndividualNum() : base() { numInvest = 0; start = 0; date = ""; } public IndividualNum(string one) : base(one) { numInvest = 16; start = 13; date = ""; } } } 

Well, the code of the form itself:

  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using System.Runtime.Serialization; namespace kursach { public partial class Form1 : Form { public List<IndividualNum> allPeople = new List<IndividualNum>(); // Все люди из расписания. private string nameOpenFile; // Изначальная видимость кнопок. public void BtnFalse() { if (dataGridView1.RowCount == 0) { this.Save.Enabled = false; this.редактироватьТабилцуToolStripMenuItem.Enabled = false; this.удалитьВыделеннуюСтрокуToolStripMenuItem.Enabled = false; this.очиститьТаблицуToolStripMenuItem.Enabled = false; this.SaveHow.Enabled = false; this.RedactButton.Enabled = false; allPeople.Clear(); } if (this.RequestDataGridView.RowCount == 0) { this.выполнитьЗапросToolStripMenuItem.Enabled = false; this.сохранитьЗапросToolStripMenuItem.Enabled = false; this.удалитьЗапросToolStripMenuItem.Enabled = false; } nameOpenFile = ""; } // Включение кнопок если таблица не пуста. public void BtnTrue() { if (this.dataGridView1.RowCount != 0) { if (nameOpenFile != "") this.Save.Enabled = true; this.SaveHow.Enabled = true; this.выполнитьЗапросToolStripMenuItem.Enabled = true; this.редактироватьТабилцуToolStripMenuItem.Enabled = true; this.удалитьВыделеннуюСтрокуToolStripMenuItem.Enabled = true; this.очиститьТаблицуToolStripMenuItem.Enabled = true; this.RedactButton.Enabled = true; } if (this.RequestDataGridView.RowCount != 0) { this.выполнитьЗапросToolStripMenuItem.Enabled = true; this.сохранитьЗапросToolStripMenuItem.Enabled = true; this.удалитьЗапросToolStripMenuItem.Enabled = true; } } // Заполнение таблицы (метод - 0 (добавление новой), 1 - изменение имеющейся, любой другой - добавление). public void AddRow(IndividualNum human, int method) { int rowCount = 0; switch (method) { case 0: this.dataGridView1.Rows.Add(); rowCount = this.dataGridView1.Rows.Count - 1; break; case 1: rowCount = this.dataGridView1.CurrentRow.Index; break; default: this.dataGridView1.Rows.Add(); rowCount = this.dataGridView1.Rows.Count - 1; break; } int cells = 0; this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.putName(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.putGender(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.putAddress(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.putBirthday(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.getNumInvest(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.getDate(); this.dataGridView1.Rows[rowCount].Cells[cells++].Value = human.getStart(); } // Конструктор формы. public Form1() { InitializeComponent(); BtnFalse(); } // Выход. private void exit_Click(object sender, EventArgs e) { //if (this.dataGridView1.RowCount == 1) this.Close(); // else // { // Сообщение о том что может сохранить? // } } // Добавление данных вкладчика. private void добавитьВкладчикаToolStripMenuItem_Click(object sender, EventArgs e) { input newInvest = new input(1); newInvest.RequestMethod = false; newInvest.ShowDialog(); if (newInvest.DontClose) { AddRow(newInvest.Invest, 0); allPeople.Add(newInvest.Invest); BtnTrue(); } } // Удаление выделенной строки. private void удалитьВыделеннуюСтрокуToolStripMenuItem_Click(object sender, EventArgs e) { if (this.dataGridView1.CurrentCellAddress.X != -1) { this.dataGridView1.CurrentRow.Selected = true; DialogResult res = MessageBox.Show("Удалить выделенную строку?\nэто путь в один конец", "Не торопись подумой", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow); if (this.dataGridView1.RowCount == 0) BtnFalse(); else BtnTrue(); } } } // Редактироание выделенной строки. private void редактироватьТабилцуToolStripMenuItem_Click(object sender, EventArgs e) { if (this.dataGridView1.CurrentCellAddress.X != -1) { this.dataGridView1.CurrentRow.Selected = true; int count = 0; foreach (IndividualNum human in allPeople) if (count == this.dataGridView1.CurrentRow.Index) { input edit = new input(human); edit.RequestMethod = false; edit.ShowDialog(); if (edit.DontClose) { AddRow(human, 1); allPeople[count] = edit.Invest; this.dataGridView1.CurrentRow.Selected = true; } break; } else count++; } } private void очиститьТаблицуToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult res = MessageBox.Show("Серъёзно? прям всю отчистить?", "Может не надо?", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { this.dataGridView1.Rows.Clear(); BtnFalse(); } } private void Open_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { dataGridView1.Rows.Clear(); BtnFalse(); //StreamReader streamReader = new StreamReader(openFileDialog1.FileName); //nameOpenFile = openFileDialog1.FileName; //string investors = streamReader.ReadToEnd(); //streamReader.Close(); nameOpenFile = openFileDialog1.FileName; XmlSerializer serializ = new XmlSerializer(typeof(List<IndividualNum>)); FileStream file = new FileStream(nameOpenFile, FileMode.Open, FileAccess.Read); allPeople = (List<IndividualNum>)serializ.Deserialize(file); file.Close(); //string[] splitInvestors = investors.Split(new char[] {';', 't'}); //int rowCount = 0, cellsCount = 0; //this.dataGridView1.Rows.Add(); //foreach (string str in splitInvestors) { // this.dataGridView1.Rows[rowCount].Cells[cellsCount++].Value = str; // if (cellsCount == 6) // { // rowCount++; // this.dataGridView1.Rows.Add(); // cellsCount = 0; // } //} //if (this.dataGridView1.RowCount != 0) //{ // BtnTrue(); // this.Save.Enabled = true; //} } } private void Save_Click(object sender, EventArgs e) { if (nameOpenFile != "") { XmlSerializer serializ = new XmlSerializer(typeof(List<IndividualNum>)); FileStream file = new FileStream(nameOpenFile, FileMode.Open, FileAccess.Write); serializ.Serialize(file, allPeople); file.Close(); } } private void SaveHow_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { nameOpenFile = saveFileDialog1.FileName; // if (nameOpenFile != "") // { //IndividualNum test = new IndividualNum(); //allPeople.Add(test); //int count = 0; //foreach (IndividualNum human in allPeople) // if (human.putName() == "1") // count++; //XmlSerializer serializ = new XmlSerializer(typeof(List<IndividualNum>)); //FileStream file = new FileStream(nameOpenFile, FileMode.Create, FileAccess.Write, FileShare.None); //serializ.Serialize(file, allPeople); //file.Close(); //XmlSerializer ser = new XmlSerializer(typeof(List<String[]>)); //StreamWriter sw = new StreamWriter(@"D:\2.xml"); //ser.Serialize(sw, allPeople); //sw.Close(); //XmlSerializer ser = new XmlSerializer(typeof(IndividualNum)); //TextWriter writer = new StreamWriter(nameOpenFile); //ser.Serialize(writer, allPeople); //writer.Close(); allPeople.Clear(); IndividualNum test = new IndividualNum("his"); allPeople.Add(test); using (FileStream fs = new FileStream(nameOpenFile, FileMode.Create, FileAccess.Write)) { XmlSerializer serializer = new XmlSerializer(allPeople.GetType()); serializer.Serialize(fs, allPeople); } //XmlSerializer xml = new XmlSerializer(typeof(IndividualNum)); //StringWriter strWriter = new StringWriter(); //xml.Serialize(strWriter, allPeople); //} //XmlTextWriter xw = new XmlTextWriter(nameOpenFile, Encoding.UTF8); //xw.Formatting = Formatting.Indented; //XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xw); //DataContractSerializer ser = new DataContractSerializer(typeof(IndividualNum)); //ser.WriteObject(writer, allPeople); //writer.Close(); //xw.Close(); } } } } 

And the code where I'm trying to serialize:

 if (saveFileDialog1.ShowDialog() == DialogResult.OK) { nameOpenFile = saveFileDialog1.FileName; // if (nameOpenFile != "") // { //IndividualNum test = new IndividualNum(); //allPeople.Add(test); //int count = 0; //foreach (IndividualNum human in allPeople) // if (human.putName() == "1") // count++; //XmlSerializer serializ = new XmlSerializer(typeof(List<IndividualNum>)); //FileStream file = new FileStream(nameOpenFile, FileMode.Create, FileAccess.Write, FileShare.None); //serializ.Serialize(file, allPeople); //file.Close(); //XmlSerializer ser = new XmlSerializer(typeof(List<String[]>)); //StreamWriter sw = new StreamWriter(@"D:\2.xml"); //ser.Serialize(sw, allPeople); //sw.Close(); //XmlSerializer ser = new XmlSerializer(typeof(IndividualNum)); //TextWriter writer = new StreamWriter(nameOpenFile); //ser.Serialize(writer, allPeople); //writer.Close(); allPeople.Clear(); IndividualNum test = new IndividualNum("his"); allPeople.Add(test); using (FileStream fs = new FileStream(nameOpenFile, FileMode.Create, FileAccess.Write)) { XmlSerializer serializer = new XmlSerializer(allPeople.GetType()); serializer.Serialize(fs, allPeople); } //XmlSerializer xml = new XmlSerializer(typeof(IndividualNum)); //StringWriter strWriter = new StringWriter(); //xml.Serialize(strWriter, allPeople); //} //XmlTextWriter xw = new XmlTextWriter(nameOpenFile, Encoding.UTF8); //xw.Formatting = Formatting.Indented; //XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xw); //DataContractSerializer ser = new DataContractSerializer(typeof(IndividualNum)); //ser.WriteObject(writer, allPeople); //writer.Close(); //xw.Close(); 

    1 answer 1

    XmlSerializer serializes public properties and fields. And in the class IndividualNum they are not.

    Do not write in java-style. Replace

     private int numInvest; private int start; private string date; public void setNumInvest(int yourInvest) { numInvest = yourInvest; } public void setStart(int yourStart) { start = yourStart; } public void setDate(string yourDate) { date = yourDate; } public int getNumInvest() { return numInvest; } public int getStart() { return start; } public string getDate() { return date; } 

    to ordinary public properties

     public int NumInvest {get; set;} public int Start {get; set;} public string Date {get; set;} 

    and by analogy make a change in Investor - and it will work.

    • Thank you very much, and how can you bypass and serialize private fields? - FireLion
    • @ AntonZhuykov corrected. XmlSerializer does not support private fields. try using DataContractSerializer - PashaPash
    • @ AntonZhuykov or implement IXmlSerializable . but it’s easier to use public fields and native C # style. - PashaPash