Write XML from a List

0

I'm developing a C # Console Application that loads a List and then writes an XML file to 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 I wanted to generate the XML in a more dynamic way, without the need to explicit the fields, only with the contents of the list.

If there is a simpler way, I accept suggestions on how to proceed.

    
asked by anonymous 15.02.2016 / 22:38

2 answers

6

You can serialize your list directly in XML , in this way;

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 some more answers.

    
16.02.2016 / 13:11
1

The solution to your problem is attached, it is worth noting that in order not to return an exception the folder where the XML will be written should 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);
            }
        }
    }
}
    
16.02.2016 / 02:51