简体   繁体   中英

How to Serialize a list of objects

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace AppPrueba
{
    public partial class Form1 : Form
    {
        ArrayList listaFilas = new ArrayList();
        public Form1()
        {
            InitializeComponent();
        }

        List<Empleados> emp = new List<Empleados>();
        List<Agenda> agen = new List<Agenda>();

        static public void SerializeToXML(List<Agenda> agen)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Agenda>));
            TextWriter textWriter = new StreamWriter(@"C:\agenda.xml");
            serializer.Serialize(textWriter, agen);
            textWriter.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog(this);
            string strfilename = openFileDialog1.FileName;

            txtPath.Text = strfilename;

            if ((strfilename.Trim().Length > 0) && (File.Exists(strfilename)))
            {
                string[] readText = File.ReadAllLines(strfilename);

                if (strfilename.EndsWith("Agenda.txt"))
                {
                    lstLinesBeforeChange.Items.Clear();
                    foreach (string s in readText)
                    {
                        lstLinesBeforeChange.Items.Add(s);
                    }
                }
                else
                {
                    lstLinesBeforeChange.Items.Clear();
                    foreach (string s in readText)
                    {
                        lstLinesBeforeChange.Items.Add(s);
                    }
                }
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            string strfilename = txtPath.Text;

            string[] readText = File.ReadAllLines(strfilename);

            if (strfilename.EndsWith("Agenda.txt"))
            {
                lstLinesAfterChange.Items.Clear();

                foreach (string s in readText)
                {
                    int nroEmp = Convert.ToInt32(s.Substring(0, 4));
                    string nombre = s.Substring(4, 15);
                    string telef = s.Substring(19, 10);
                    string ciudad = s.Substring(29);

                    Agenda unAgenda = new Agenda();

                    unAgenda.NroEmp = nroEmp;
                    unAgenda.Nombre = nombre.TrimStart().TrimEnd();
                    unAgenda.Telefono = telef;
                    unAgenda.Localidad = ciudad;

                    agen.Add(unAgenda);

                    agen.Sort(delegate(Agenda a1, Agenda a2)
                    {
                        return a1.NroEmp.CompareTo(a2.NroEmp);
                    });
                }

                foreach (Agenda a in agen)
                {
                    string agenOrd = a.NroEmp.ToString() + "\t" + a.Nombre + "\t" + a.Telefono + "\t" + a.Localidad;

                    lstLinesAfterChange.Items.Add(agenOrd);
                }
            }
            else
            {
                lstLinesAfterChange.Items.Clear();
                foreach (string s in readText)
                {
                    string[] sSinBarra = s.Split('|');

                    int nroEmp = Convert.ToInt32(sSinBarra[0]);
                    string nombre = sSinBarra[1];
                    string posicion = sSinBarra[2];
                    int nroOficina = Convert.ToInt32(sSinBarra[3]);
                    int piso = Convert.ToInt32(sSinBarra[4]);
                    string fechaIng = sSinBarra[5];

                    int dia = Convert.ToInt32(fechaIng.Substring(0, 2));
                    int mes = Convert.ToInt32(fechaIng.Substring(2, 2));
                    int año = Convert.ToInt32(fechaIng.Substring(4, 4));
                    string fechaIngreso = dia + "/" + mes + "/" + año;
                    fechaIng = fechaIngreso;

                    Empleados unEmpleado = new Empleados();

                    unEmpleado.NroEmpleado1 = nroEmp;
                    unEmpleado.Nombre1 = nombre.TrimEnd().TrimStart();
                    unEmpleado.Posicion = posicion.TrimEnd().TrimStart();
                    unEmpleado.NroOficina = nroOficina;
                    unEmpleado.Piso = piso;
                    unEmpleado.FechaIngreso = fechaIngreso;

                    emp.Add(unEmpleado);

                    emp.Sort(delegate(Empleados e1, Empleados e2)
                    {
                        return e1.NroEmpleado1.CompareTo(e2.NroEmpleado1);
                    });
                }

                foreach (Empleados em in emp)
                {
                    string empOrd = em.NroEmpleado1.ToString() + "\t" + em.Nombre1 + "\t" + em.Posicion + "\t" + em.NroOficina.ToString()
                        + "\t" + em.Piso.ToString() + "\t" + em.FechaIngreso;

                    lstLinesAfterChange.Items.Add(empOrd);
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            //saveFileDialog1.ShowDialog();

            //if (saveFileDialog1.FileName != "")
            //{
            //    FileStream fs = (FileStream)saveFileDialog1.OpenFile();

            //    fs.Close();

            //}
            SerializeToXML(agen);

        }
    }
}

I have this, and i want to serialize to xml both lists :

List<Empleados> emp = new List<Empleados>();
List<Agenda> agen = new List<Agenda>();

I used SerializeToXML method that i found in other tutorial but when i run it an error shows up

"Error 1 Inconsistent accessibility: parameter type 'System.Collections.Generic.List' is less accessible than method 'AppPrueba.Form1.SerializeToXML(System.Collections.Generic.List)' C:\\Users\\722825\\Desktop\\Santi Cosas\\AppPrueba\\AppPrueba\\Form1.cs 27 28 AppPrueba"

Thanks in advance if you can help me!

All the classes that you are trying to serialize to xml should be public. And for collection serialization you cannot use generics - either use untyped collections, like, ArrayList , or create a non-generic descendant class form List .

agen is private and SerializeToXML is public static. You need agen public

Your error says that the variabel List agen = new List(); needs to be public like this: public List agen = new List();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM