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>