How to mount XML with C #?

1

I need to mount an XML as in the following example:

<?xml version="1.0" encoding="utf-8"?> 
<MeuXML>
   <Clientes>  
        <Cliente-1>Dados Cliente-1</Cliente>  
   </Clientes> 
   <Sistemas>   
        <Sistema-1>
            <Pasta>Pasta do Sistema-1</Pasta>
            <Origem>Origem do Sistema-1</Fontes>    
        </Sistema-1>
   </Sistemas>
</MeuXMl>

I can even build an empty initial XML, but when I add a new client for example (such as Client-1), my code duplicates the Customers tag. The same thing happens with systems. I'm doing this with systems (System-1 example):

 XElement xml = XElement.Load("Config.xml")
 XElement xmlSistemas = XElement.Load("Config.xml").Elements("Sistemas").FirstOrDefault();
 XElement xSistema1 = new XElement("Sistema-1");
 XElement xPasta = new XElement("Pasta");
 xPasta.Value = "Pasta do Sistema-1";
 XElement xOrigem = new XElement("Origem");
 xOrigem.Value = "Origem do Sistema-1";
 xSistema1.Add(xPasta, xOrigem);
 xmlSistemas.Add(xSistema1);
 xml.Add(xmlSistemas);
 xml.Save("Config.xml");

How can I fix this? Thanks!

    
asked by anonymous 08.01.2016 / 18:22

1 answer

3

You're adding the <Sistemas> (and your children) tag you created in the xml file (MyXML tag), which already has a Sistemas tag - so you get two. What you need to do is to add the new system ( xSistema1 ) to the Sistemas tag that already exists in the file. The code below shows how this can be done.

class Program
{
    const string XML = @"<?xml version=""1.0"" encoding=""utf-8""?> 
<MeuXML>
   <Clientes>  
        <Cliente-1>Dados Cliente-1</Cliente-1>  
   </Clientes> 
   <Sistemas>   
        <Sistema-1>
            <Pasta>Pasta do Sistema-1</Pasta>
            <Origem>Origem do Sistema-1</Origem>    
        </Sistema-1>
   </Sistemas>
</MeuXML>";

    static void Main(string[] args)
    {
        XElement xml = XElement.Parse(XML);
        XElement xmlSistemas = xml.Elements("Sistemas").FirstOrDefault();
        XElement xSistema2 = new XElement("Sistema-2");
        XElement xPasta = new XElement("Pasta");
        xPasta.Value = "Pasta do Sistema-2";
        XElement xOrigem = new XElement("Origem");
        xOrigem.Value = "Origem do Sistema-2";
        xSistema2.Add(xPasta, xOrigem);
        xmlSistemas.Add(xSistema2);
        Console.WriteLine(xml);
    }
}
    
08.01.2016 / 18:39