Generate an xml in c#

Asked

Viewed 2,971 times

4

I need to create an application, where the data will be saved in a local xml and then sent to a server using wcf. However I am with the following doubts what I do in the client and what I do in the service (wcf). I’m new in this area and I have no idea where to start?

3 answers

6

You can do it with LINQ to XML, it’s very simple. I made a very basic example to make it easy to understand:

public class Pessoa
{
    public string Nome { get; set; }
    public int Idade { get; set; }

    public Pessoa(string nome, int idade)
    {
        Nome = nome;
        Idade = idade;
    }
}

public static void Escrever()
{
    var pessoas = new[] { new Pessoa("Fulano", 10), new Pessoa("Ciclano", 20) };

    var xml = new XDocument(new XElement("Pessoas",
                                        pessoas.Select(p => new XElement("Pessoa",
                                            new XAttribute("Nome", p.Nome),
                                            new XAttribute("Idade", p.Idade)))));
    xml.Save("pessoas.xml");
}

public static void Ler()
{
    var xml = XDocument.Load("pessoas.xml");

    Pessoa[] pessoas = xml.Element("Pessoas").Elements("Pessoa")
                       .Select(x => new Pessoa(x.Attribute("Nome").Value,
                                               int.Parse(x.Attribute("Idade").Value))).ToArray();
}

Upshot:

<?xml version="1.0" encoding="utf-8"?>
<Pessoas>
  <Pessoa Nome="Fulano" Idade="10" />
  <Pessoa Nome="Ciclano" Idade="20" />
</Pessoas>

Here’s a link from the most detailed Macoratti website: http://www.macoratti.net/09/02/lnq_xml1.htm

4

Using the Vitor model, you can also use the attribute class Serializable:

[Serializable]
public class Pessoa
{
    public string Nome { get; set; }
    public int Idade { get; set; }
    public Pessoa()
    {

    }
    public Pessoa(string nome, int idade)
    {
        Nome = nome;
        Idade = idade;
    }


    public static void Escrever()
    {
        Pessoa[] pessoas = new[] { new Pessoa("Fulano", 10), new Pessoa("Ciclano", 20) };

        System.Xml.Serialization.XmlSerializer Serializer = new System.Xml.Serialization.XmlSerializer(typeof(Pessoa[]));

        using (System.IO.TextWriter Write = new System.IO.StreamWriter("pessoas.xml", true))
        {
            Serializer.Serialize(Write, pessoas);
            Write.Close();
        }
    }

    public static Pessoa Ler()
    {
        System.Xml.Serialization.XmlSerializer Serializer = new System.Xml.Serialization.XmlSerializer(typeof(Pessoa));
        Pessoa pessoas = null;
        using (System.IO.TextReader Reader = new System.IO.StreamReader("pessoas.xml"))
        {
            pessoas = Serializer.Deserialize(Reader) as Pessoa;
            Reader.Close();
        }

        return pessoas;
    }
}

4

What you want is a database environment, in loco, to work with your app in mode offline and, when you have a connection, sync this data. Right?

Well, as it was not said whether it is a desktop or mobile app, or assume it is using . NET Framework full, that is, a desktop app.

For these cases, exclusively, I recommend using System.Data.Dataset. Dataset is a representation, I remember, of a database. With it you can simulate an entire database, creating tables, making relationship, even controlling transaction.

But the Feature most important in your case is that it already has methods to record and retrieve information in XML. See:

var dataSet = new DataSet();
dataSet.Tables.Add(new DataTable("Tabela1"));
dataSet.WriteXml(@"c:\bancodedados.xml");

Your scenario fits very well to use this guy. It is super easy to implement, and already has features to save and recover local XML data.

However, note that it is not recommended - by me at least - to use this guy in any scenario. In your, specifically, it.

A few months ago I wrote an article discouraging to use for its complexity. Talking about the Dataset and Datatable evils. Worth a look at.

  • So, I have an application(desktop) where the client will return an object. Ai in the service (wcf) I have to create an xml where this object will be saved. The xml has to be created and saved on the machine, and after it is generated, using a send file to the database. I cannot save in memory, because then I will have several users using this application and send the data to the xml and saving on the server.

  • @Luciano, do not understand why not keep in memory since XML will be generated in the WCF service. Play XML in Cache and distribute among users. Saving data on application disk is a bad practice.

Browser other questions tagged

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