Save XML from a List

Asked

Viewed 793 times

0

I am developing a C# Console Application that loads a List and then writes an XML file with the contents of this List.

Class

public class Equipamento

    {
        public int Id { get; set; }
        public string Marca { get; set; }
        public int Ano { get; set; }

    }

I’m writing XML like this:

private void GravaListXMLinq(List<Equipamento> ListaEquipamentos)
{
    string caminho = @"D:\XML\saida.xml";
    try
    {
        var xEle = new XElement("Equipamentos",
                    from emp in ListaEquipamentos
                    select new XElement("Equipamento",
                                    new XAttribute("ID", emp.Id),
                                    new XElement("Marca", emp.Marca),
                                    new XElement("Ano", emp.Ano)
                               ));
        xEle.Save(caminho);
        this.Log().Info("Arquivo XLM gravado em: " + caminho);
    }
    catch (Exception ex)
    {
        this.Log().Error("Ao gravar XML em: " + caminho + " Erro: " + ex.Message);
    }
}

It works, but wanted to generate XML more dynamically, without the need to clarify the fields, only with the contents of the list.

If there is any other simpler way I accept suggestions on how to proceed.

  • 1

    What do you mean sem a necessidade de explicitar os campos?

  • In the select I have to put the names of the fields new XAttribute("ID", emp.Id and didn’t want to have this job.

2 answers

6


You can serialize your list directly on XML, thus;

private void GravaListXMLinq(List<Equipamento> ListaEquipamentos)
{
    string caminho = @"D:\XML\saida.xml";
    try
    {
            //cria o serializador da lista
            XmlSerializer serialiser = new XmlSerializer(typeof(List<Equipamento>));

            //Cria o textWriter com o arquivo
            TextWriter filestream = new StreamWriter(caminho);

            //Gravação dos arquivos
            serialiser.Serialize(filestream, ListaEquipamentos);

            //Fecha o arquivo
            filestream.Close();

            this.Log().Info("Arquivo XLM gravado em: " + caminho);
    }
    catch (Exception ex)
    {
        this.Log().Error("Ao gravar XML em: " + caminho + " Erro: " + ex.Message);
    }
}

The simplest way I found was this (although I like to define the field names, as it is in your question).

If you want more examples, this question has a few more answers.

  • Ih comrade how long!? Thanks worked as expected. Thank you very much.

  • @Jota It’s been a while. I’m glad it worked, anything just let me know.

1

Follows in attachment the solution to your problem, it is valid to emphasize that not to return an exception to the folder where the XML will be written must actually exist.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    public class Equipamento
    {
        public int Id { get; set; }
        public string Marca { get; set; }
        public int Ano { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var lista = new List<Equipamento> {
                new Equipamento { Ano = 1990, Id = 1, Marca = "1"},
                new Equipamento { Ano = 1990, Id = 2, Marca = "2"},
            };
            GravaListXMLinq(lista);
        }

        private static void GravaListXMLinq(List<Equipamento> listaEquipamentos)
        {
            const string caminho = @"C:\XML\saida.xml";
            try
            {
                XmlSerializer xsSubmit = new XmlSerializer(typeof(List<Equipamento>));
                var subReq = listaEquipamentos;
                using (var sww = new StringWriter())
                {
                    using (var writer = XmlWriter.Create(sww))
                    {
                        xsSubmit.Serialize(writer, subReq);
                        var xml = sww.ToString();
                        XDocument doc = XDocument.Parse(xml);
                        XElement root = doc.Root;
                        root.Save(caminho);
                        //this.Log().Info("Arquivo XLM gravado em: " + caminho);
                    }
                }
            }
            catch (Exception ex)
            {
                //this.Log().Error("Ao gravar XML em: " + caminho + " Erro: " + ex.Message);
            }
        }
    }
}
  • That part XmlSerializer(typeof (MyObject)); this with error. I changed to typeof(Equipamento), but generates an XML with nothing. What should I use? But I appreciate the help.

  • Comment, I updated the code I wrote collecting several references and as I was on the phone I did not write properly

  • However it follows a code tested and functional, pardon.

  • Thanks for the help. Now it’s working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.