XML/C# - How to create tags containing other tags within it

Asked

Viewed 825 times

3

Allah Personal I have the following problem: I need to create an xml file of products, in which each product will have a group, so far so good, just by adding the data it creates the product tag and within it creates the group, only by creating the product and going to add the group it is always doing as follows finds the first product tag and adds all groups. So how would I make it to always add group to the latest product tag.

Expected result:

<?xml version="1.0"?>    
-<fdv>    
<data>05/12/2012 17:41:08</data>    
<vendedor>V001</vendedor>   

-<valores>  

-<produto>    
<codigoImport>000083</codigoImport>    
<descricao>MAÇANETA GOL</descricao>    
<un>PÇ</un>    
<precoVenda>12.5</precoVenda>    
<estoque>180</estoque>    
<codBarras>00000833</codBarras>    
<url>http://user.img.todaoferta.uol.com.br/5/P/JO/NDEDP</url>    
<obs>Aplicado em veículo modelo: 2001 2002 2003</obs>    
-<grupo>    
<codigoImport>1001</codigoImport>    
<descricao>PORTAS</descricao>    
</grupo>    
</produto>   

-<produto>    
<codigoImport>000084</codigoImport>    
<descricao>MAÇANETA PALIO</descricao>    
<un>PÇ</un>    
<precoVenda>15</precoVenda>    
<estoque>200</estoque>    
<codBarras>00000840</codBarras>    
<url>http://www.takamineacessorios.com.br/prdfotos/prd_</url>    
<obs>Aplicados em modelos: 2006 2007 2008 2009 2010</obs> 

-<grupo>    
<codigoImport>1001</codigoImport>    
<descricao>PORTAS</descricao>    
</grupo>    
</produto>        
</valores>    
</fdv>

This is my code according to the example of Marco Antonio Quintal, now as I said he is only creating the last record:

#define Windows_Application
using System;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Collections;
using System.Xml.Linq;
using System.Xml.XPath;

namespace GSD
{
    class XmlProduto3
    {
        //Diretorio do arquivo Xml;
        private string diretorioArqXml()
        {
            string diretorio = Directory.GetCurrentDirectory();
            string mensagem = String.Empty;
            string caminho = diretorio.Trim() + @"\XML\";

            if (!Directory.Exists(caminho))
            {
                Directory.CreateDirectory(caminho);
            }
            return caminho;
        }

        //Cria o arquivo Xml;
        public void criarArqXml()
        {
            string caminho = diretorioArqXml() + "impprodutos.xml";
            string sqlFunCod = @"SELECT FUNCOD FROM SYS_USUARIO WHERE CODUSU = " + Engebuilder.Library.ConstEngebuilder.codUsu.ToString().Trim() + "";
            string funcod = Engebuilder.Library.LDataAccess.GetDataToString(sqlFunCod);
            Engebuilder.Library.LDataAccess.ExecuteCommand(sqlFunCod);

            ArrayList VlrProCod = new ArrayList();
            ArrayList VlrProDes = new ArrayList();
            ArrayList VlrProUni = new ArrayList();
            ArrayList VlrProPrc = new ArrayList();
            ArrayList VlrProEst = new ArrayList();
            ArrayList VlrProCodBar = new ArrayList();
            ArrayList VlrProCodGrp = new ArrayList();
            ArrayList VlrProDesGrp = new ArrayList();

            DataSet ds = Engebuilder.Library.LDataAccess.GetDataSet("SELECT "
            + " PRODUTO.PROCOD, "
            + " PRODUTO.PRODESRDZ, "
            + " PRODUTO.PROUNID, "
            + " PRODUTO.PROPRCVDAVAR, "
            + " ESTOQUE.ESTATU, "
            + " PRODUTOAUX.PROCODAUX, "
            + " PRODUTO.GRPCOD, "
            + " GRUPO.GRPDES "
            + " FROM PRODUTO "
            + " INNER JOIN ESTOQUE ON ESTOQUE.PROCOD = PRODUTO.PROCOD "
            + " LEFT JOIN PRODUTOAUX ON PRODUTOAUX.PROCOD = PRODUTO.PROCOD "
            + " LEFT JOIN GRUPO ON GRUPO.GRPCOD = PRODUTO.GRPCOD "
            + " ORDER BY PRODUTO.PROCOD");

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                VlrProCod.Add(row["PROCOD"].ToString().Trim());
                VlrProDes.Add(row["PRODESRDZ"].ToString().Trim());
                VlrProUni.Add(row["PROUNID"].ToString().Trim());
                VlrProPrc.Add(row["PROPRCVDAVAR"].ToString().Trim());
                VlrProEst.Add(row["ESTATU"].ToString().Trim());
                VlrProCodBar.Add(row["PROCODAUX"].ToString().Trim());
                VlrProCodGrp.Add(row["GRPCOD"].ToString().Trim());
                VlrProDesGrp.Add(row["GRPDES"].ToString().Trim());
            }

            for (int i = 0; i < VlrProCod.Count; i++)
            {
                XDocument doc = new XDocument(
                  new XElement("fdv",
                    new XElement("data", DateTime.Now.ToString()),
                    new XElement("vendedor", funcod),
                    new XElement("produto",
                      new XElement("codigoImport", VlrProCod[i].ToString()),
                      new XElement("descricao", VlrProDes[i].ToString()),
                      new XElement("un", VlrProUni[i].ToString()),
                      new XElement("precoVenda", VlrProPrc[i].ToString()),
                      new XElement("estoque", VlrProEst[i].ToString()),
                      new XElement("grupo",
                        new XElement("codigoImport", VlrProCodGrp[i].ToString()),
                        new XElement("descricao", VlrProDesGrp[i].ToString()
                  )
                )
              )
            )
          );

                doc.Save(caminho);
            }
            MessageBox.Show("Dados exportado com sucesso!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

2 answers

4

That’s right Folks, thank you so much for the help the correct code has now come this way:

#define Windows_Application
using System;
using System.Data;
using System.Windows.Forms;

using System.Management;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Collections;
using System.Xml.Linq;
using System.Xml.XPath;

namespace GSD
{
    public class XmlProduto
    {
        public XmlProduto()
        {
        }   

        //Diretorio do arquivo Xml;
        private string diretorioArqXml()
        {
            string diretorio = Directory.GetCurrentDirectory();
            string mensagem = String.Empty;
            string caminho = diretorio.Trim() + @"\XML\";

            if (!Directory.Exists(caminho))
            {
                Directory.CreateDirectory(caminho);
            }
            return caminho;
        }

        //Cria o arquivo Xml;
        public void criarArqXml()
        {
            try
            {
                string caminho = diretorioArqXml() + "impprodutos.xml";

                string sqlFunCod = @"SELECT FUNCOD FROM SYS_USUARIO WHERE CODUSU = " + Engebuilder.Library.ConstEngebuilder.codUsu.ToString().Trim() + "";
                string funcod = Engebuilder.Library.LDataAccess.GetDataToString(sqlFunCod);
                Engebuilder.Library.LDataAccess.ExecuteCommand(sqlFunCod);

                string VlrProCod = String.Empty;
                string VlrProDes = String.Empty;
                string VlrProUni = String.Empty;
                string VlrProPrc = String.Empty;
                string VlrProEst = String.Empty;
                string VlrProCodBar = String.Empty;
                string VlrProCodGrp = String.Empty;
                string VlrProDesGrp = String.Empty;

                DataSet ds = Engebuilder.Library.LDataAccess.GetDataSet("SELECT "
                  + " PRODUTO.PROCOD, "
                  + " PRODUTO.PRODESRDZ, "
                  + " PRODUTO.PROUNID, "
                  + " PRODUTO.PROPRCVDAVAR, "
                  + " ESTOQUE.ESTATU, "
                  + " PRODUTOAUX.PROCODAUX, "
                  + " PRODUTO.GRPCOD, "
                  + " GRUPO.GRPDES "
                  + " FROM PRODUTO "
                  + " INNER JOIN ESTOQUE ON ESTOQUE.PROCOD = PRODUTO.PROCOD "
                  + " LEFT JOIN PRODUTOAUX ON PRODUTOAUX.PROCOD = PRODUTO.PROCOD "
                  + " INNER JOIN SECAO ON SECAO.SECCOD = PRODUTO.SECCOD "
                  + " INNER JOIN GRUPO ON (GRUPO.SECCOD = SECAO.SECCOD "
                  + " AND GRUPO.GRPCOD = PRODUTO.GRPCOD) "
                  + " INNER JOIN SUBGRUPO ON (SUBGRUPO.SECCOD = SECAO.SECCOD "
                  + " AND SUBGRUPO.GRPCOD = GRUPO.GRPCOD "
                  + " AND SUBGRUPO.SGRCOD = PRODUTO.SGRCOD) "
                  + " ORDER BY PRODUTO.PROCOD");


                //Verrifica se o arquivo existe, caso sim o deleta;
                if (File.Exists(caminho))
                {
                    File.Delete(caminho);
                }

                XElement doc = new XElement("fdv");

                doc.Add(new XElement("data", DateTime.Now.ToString()));
                doc.Add(new XElement("vendedor", funcod));
                XElement valores = new XElement("valores");

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    VlrProCod = row["PROCOD"].ToString().Trim();
                    VlrProDes = row["PRODESRDZ"].ToString().Trim();
                    VlrProUni = row["PROUNID"].ToString().Trim();
                    VlrProPrc = row["PROPRCVDAVAR"].ToString().Trim();
                    VlrProEst = row["ESTATU"].ToString().Trim();
                    VlrProCodBar = row["PROCODAUX"].ToString().Trim();
                    VlrProCodGrp = row["GRPCOD"].ToString().Trim();
                    VlrProDesGrp = row["GRPDES"].ToString().Trim();

                    valores.Add(new XElement("produto",
                      new XElement("codigoImport", VlrProCod),
                      new XElement("descricao", VlrProDes),
                      new XElement("un", VlrProUni),
                      new XElement("precoVenda", VlrProPrc),
                      new XElement("estoque", VlrProEst),
                      new XElement("codBarras", VlrProCodBar),
                      new XElement("url", null),
                      new XElement("obs", null),
                      new XElement("grupo",
                        new XElement("codigoImport", VlrProCodGrp),
                        new XElement("descricao", VlrProDesGrp)
                        )
                       )
                     );
                }

                doc.Add(valores);
                doc.Save(caminho);
                MessageBox.Show("Dados exportado com sucesso!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception)
            {

                MessageBox.Show("Ocorreu um erro gerar o arquivo XML!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

3


You must use the class Xdocument

Sort of like this to create the sublevels:

        new XElement("fdv",
            new XElement("vendedor", "V001"),
            new XElement("produto",
                new XElement("codigoImport", "000083"),
                new XElement("grupo",
                    new XElement("codigoImport", "1001")
                )
            )
        )
        .Save("produtos.xml");

I hope I helped. Any problem send a comment that I reply.

Complementing the answer: after you added more code, declare the XDocument and the root element outside the for, and add the other elements in for.

  • Hello, I did as you suggested but I’m still with a problem, is that I have a list of products, no add them in an Arraylist and then use a FOR for the creation of XML, only that it is only creating the last record is as if it is overwriting the data.

  • 1

    Declare Xdocument out of for. Ex: Xdocument doc;

  • Blz, send you the invitation below I also put the previous code I was doing and also according to your example.

  • Even though having declared him out of the will still continue only getting the last record.

  • Dude I must be in some trouble, rsrsrsrsrs. I’ve remade I went back to the previous one and nothing, continue everything the same way both in one and the other.

  • @Joaquimcaetanoteixeira, do as Marco said, put the XDocument outside the for, something like that XDocument doc = new XDocument();, there inside the for instead of creating a new XDocument, you do doc.Add(new XElement("fdv", ...); (dots represent the rest of the code). Another detail, use the doc.Save(caminho); outside the for also.

Show 1 more comment

Browser other questions tagged

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