Handling XML Files in C # - Library Tips [closed]

1

I need to manipulate an XML file in C #. This is the first time I'm going to do this, and I wanted some tips. My algorithm is basically this:

  • Fill an XML from my system data (DB Data)

    Ex: I have an entity from which my example data comes Person, that the same by its turn has its attributes.

    I need to get this data from Person, and set up an xml.

  • Read this generated XML file, for execution of an X algorithm, that will perform calculations based on my XML data.

    This algorithm will provide me with new data as the results of my study.

  • I need tips on:

    In short, what I want is:

    • Generate an xml with my entity data,
    • read this file populating a result entity.
    • Export my result to xml.

    My question is:

    1 - What Lib can I use to manipulate these files? That is, there is a library I can use to help me manipulate xml files in C #. What I mean is, so you do not have to do everything in the hand?

    2 - Does anyone have an example that you can give me, or any tips on how I can accomplish this task?

    3 - Lib to automate this task?

    Thank you.

        
  • asked by anonymous 13.07.2017 / 16:25

    1 answer

    2

    OC # provides some classes ( XmlSerializer, StreamWriter, StreamReader, etc ...) of the namespaces System.Xml and System.IO that you can use to handle files and do XML serialization.

    If you can not find a Lib to automate, here's an example:

    using System.IO;
    using System.Xml.Serialization;
    
    class Program
    {
        static void Main(string[] args)
        {
            // Gerar um xml com os dados de minha entidade
    
            var pessoa = new Pessoa { Id = 1, Nome = "Renan" };
    
            var xmlSerializer = new XmlSerializer(typeof(Pessoa));
            StreamWriter streamWriter = new StreamWriter("pessoa.xml");
    
            xmlSerializer.Serialize(streamWriter, pessoa);
    
            streamWriter.Close();
    
            // ler esse arquivopopulando uma entidade de resultados.
            // Exportar meu resultado para xml.
    
            FileStream meuFileStream = new FileStream("pessoa.xml", FileMode.Open);
    
            Pessoa _pessoa = (Pessoa)xmlSerializer.Deserialize(meuFileStream);
    
            Console.WriteLine(_pessoa.Nome); // Imprime "Renan"
            Console.ReadLine();
        }
    }
    
    public class Pessoa
    {
        public int Id { get; set; }
    
        public string Nome { get; set; }
    }
    

    Xml generated and saved in file "... \ bin \ Debug \ person.xml":

    <?xml version="1.0" encoding="utf-8"?>
    <Pessoa xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Id>1</Id>
      <Nome>Renan</Nome>
    </Pessoa>
    
        
    13.07.2017 / 19:01