2

So I have to import an XML document to SQL, but the catch here is if you import an attribute that doesn't appear in the the table, the XML attribute won't appear in the table, and if all the attributes that the table has aren't filled up wit the XML, it will appear as Null.

So an easy example: If the XML document has three attributes, but only one is in the SQL Server table, it will only show that one.

XML

EmployeeID 123456                               
Country                                 
Phone                                    

SQL

EmployeeID 123456
Name       Null 
Last Name  Null

So my Question is, which instruction or what code I have to put and where?

And is this instruction indeed needed?:

Here is the code in C#:

/*System.Xml.XmlTextReader lee = new System.Xml.XmlTextReader(archivo);
        string contents = "";
        while (lee.Read())
        {
            lee.MoveToContent();
            if (lee.NodeType == System.Xml.XmlNodeType.Element)
            {
                contents += "<" + lee.Name + ">\n";
                */

Full Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;

namespace XML_A_BD
{
    public partial class Form1 : Form
    {
        string archivo = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strConn = "Data Source=(LOCAL);Initial Catalog=master;Integrated Security=true";
            string strSQL = "SELECT name FROM sys.databases order by name";
            SqlConnection scnnRegistro = new SqlConnection(strConn);
            SqlCommand scmd = new SqlCommand(strSQL, scnnRegistro);
            try
            {
                scnnRegistro.Open();
                SqlDataReader sdr = scmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (sdr.Read())
                {
                    comboBoxBase.Items.Add(sdr.GetString(0).ToString());
                }
                sdr.Close();
                comboBoxBase.SelectedIndex = 0;
            }
            catch (SqlException expSql)
            {
                MessageBox.Show(expSql.ToString());
            }

        }

        private void comboBoxBase_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strConn = "Data Source=(LOCAL);Initial Catalog =master;Integrated Security=SSPI";
            string strSQL = "SELECT name FROM " + comboBoxBase.SelectedItem.ToString();
            strSQL += ".sys.objects where type = 'U' order by name";
            MessageBox.Show(strSQL);
            SqlConnection scnnRegistro = new SqlConnection(strConn);
            SqlCommand scmd = new SqlCommand(strSQL, scnnRegistro);
            try
            {
                scnnRegistro.Open();
                SqlDataReader sdr = scmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (sdr.Read())
                {
                    comboBoxTabla.Items.Add(sdr.GetString(0).ToString());
                }
                sdr.Close();
            }
            catch (SqlException expSql)
            {
                MessageBox.Show(expSql.ToString());
            }
            comboBoxTabla.SelectedIndex = 0;
        }

        private void buttonSalir_Click(object sender, EventArgs e)
        {
            DialogResult dialog = MessageBox.Show("Seguro que desea salir?", "Salir", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialog == DialogResult.Yes)
            {
                this.Dispose();
            }
        }

        private void buttonSeleccionar_Click(object sender, EventArgs e)
        { 
            try
            {
                OpenFileDialog abrir = new OpenFileDialog();
                abrir.Filter = "Archivos XML(*.xml)|*.xml|Todos los archivos(*.*)|*.*";
                abrir.FilterIndex = 0;
                abrir.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //guardar.Filename = tabla;
                if (abrir.ShowDialog() == DialogResult.OK)
                {
                    archivo = abrir.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonCargar_Click(object sender, EventArgs e)
        {
            bool bandera = false;
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(archivo);
                XmlNodeList dataNodes = xmlDoc.SelectNodes("/" + comboBoxBase.SelectedItem.ToString() + "/" + comboBoxTabla.SelectedItem.ToString());

                foreach (XmlNode node in dataNodes)
                {
                    string sql = "";

                    XmlNodeList lstNodos = node.ChildNodes;
                    MessageBox.Show(lstNodos.Count.ToString());
                    int contador = 0;
                    string[] atributos = new string[lstNodos.Count];
                    string[] valores = new string[lstNodos.Count];
                    sql = "Insert into " + comboBoxBase.SelectedItem.ToString();
                    sql = sql + ".." + comboBoxTabla.SelectedItem.ToString() + " values (";
                    foreach (XmlNode nodoHijo in lstNodos)
                    {
                        //MessageBox.Show(nodoHijo.Name); //Nombre de la etiqueta del nodo
                        //MessageBox.Show(nodoHijo.InnerText);
                        atributos[contador] = "@" + nodoHijo.Name;
                        valores[contador] = nodoHijo.InnerText;
                        sql = sql + (++contador < lstNodos.Count ? "@" + nodoHijo.Name + "," : "@" + nodoHijo.Name);                        
                    }
                    sql = sql + ")";
                    //sql = "insert into banco..prestamo values(1,1,6,3000.00)";
                    MessageBox.Show(sql);
                    try
                    {
                        string conexion = "Data Source=(local);Initial Catalog=master;Integrated Security=SSPI";
                        SqlConnection conn = new SqlConnection(conexion);
                        //using (command = new SqlCommand(sql, conn));
                        SqlCommand comando = new SqlCommand(sql, conn);
                        for (int i = 0; i < lstNodos.Count; i++)
                        {
                            //comando.Parameters.AddWithValue(atributos[i], (i < 3 ? int.Parse(valores)))
                            comando.Parameters.AddWithValue(atributos[i], valores[i]);
                            MessageBox.Show(atributos[i] + " " + valores[i]);
                        }
                        conn.Open();
                        comando.ExecuteNonQuery();
                        conn.Close();
                    }
                    catch (SqlException expSql)
                    {
                        bandera = true;
                        MessageBox.Show(expSql.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (bandera == true)
            {
                MessageBox.Show("Se omitieron valores repetidos. Exportacion completa.", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Exportacion a SQL correcta", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

XML:

<?xml version="1.0" standalone="yes"?>
<cliente>
  <cliente>
    <no_cliente>6</no_cliente>
    <nombre>Luis</nombre>
    <ap_paterno>Franco</ap_paterno>
    <ap_materno>Cárdenas</ap_materno>
    <calle>Sadi Carnot</calle>
    <ciudad_cliente>Distrito Federal</ciudad_cliente>
    <password>6</password>
  </cliente>
  <cliente>
    <no_cliente>7</no_cliente>
    <nombre>Alberto</nombre>
    <ap_paterno>Marín</ap_paterno>
    <ap_materno>Pérez</ap_materno>
    <calle>Principal</calle>
    <ciudad_cliente>Distrito Federal</ciudad_cliente>
    <password>7</password>
  </cliente>
  <cliente>
    <no_cliente>8</no_cliente>
    <nombre>Roberto</nombre>
    <ap_paterno>López</ap_paterno>
    <ap_materno>Mora</ap_materno>
    <calle>Altavista</calle>
    <ciudad_cliente>Guadalajara</ciudad_cliente>
    <password>8</password>
  </cliente>
  <cliente>
    <no_cliente>9</no_cliente>
    <nombre>Andrea</nombre>
    <ap_paterno>Carrillo</ap_paterno>
    <ap_materno>Méndez</ap_materno>
    <calle>Primavera</calle>
    <ciudad_cliente>Monterrey</ciudad_cliente>
    <password>9</password>
  </cliente>
  <cliente>
    <no_cliente>10</no_cliente>
    <nombre>Daniela</nombre>
    <ap_paterno>Torres</ap_paterno>
    <ap_materno>Gordillo</ap_materno>
    <calle>Ing. Militares</calle>
    <ciudad_cliente>Naucalpan</ciudad_cliente>
    <password>10</password>
  </cliente>
  <cliente>
    <no_cliente>11</no_cliente>
    <nombre>Pedro</nombre>
    <ap_paterno>López</ap_paterno>
    <ap_materno>Zamorano</ap_materno>
    <calle>Barracuda</calle>
    <ciudad_cliente>Veracruz</ciudad_cliente>
    <password>11</password>
  </cliente>
</cliente>
  • Your way of constructing SQL by concatenating strings is not good. Check theese answers http://dba.stackexchange.com/a/106230/44324 or http://stackoverflow.com/a/16839209/2224701. I would prefer to directly read XML form SQL server than to read it by C# and then import it to SQL table. – Vojtěch Dohnal Apr 21 '16 at 09:01
  • Maybe I do not get this correctly: Are you trying to create an XML and pass this over to SQL Server in order to store the values in a table? Where is the data? Why XML? Why do you create the XML via string concatenation? – Shnugo Apr 21 '16 at 09:21
  • Sorry, I'm kinda dumb with words when I'm tired. With an existing XML pass it to SQL. And I realize now that I forgot the XML. Going to edit it. Vojtěch Dohnal. My teacher left us that as a project. It has to get from XML -> C# -> SQL – Marco Diez Barroso Zamudio Apr 21 '16 at 09:34
  • So in my words: Version 1: There is an XML (a file?), you load it with C# and pass it over to SQL in order to store the data in tables? Or version 2: There is data from somewhere, you have to read this somehow with C#, than you have to built the XML *within* C# and pass it over to SQL Server? Are you allowed to pass the XML to SQL Server *as is* and do the shredding there? – Shnugo Apr 21 '16 at 10:15
  • The first version. I don't know how to put the null data if it doesn't match and if it matches with the name to import the data to sql. – Marco Diez Barroso Zamudio Apr 21 '16 at 17:12

0 Answers0