【发布时间】:2016-04-20 21:48:02
【问题描述】:
这是将数据从 XML 文档导入 SQL 的代码,我不知道该怎么做是如果 XML 属性的名称与表上的 SQL 属性之一匹配,则导入仅匹配属性,如果不匹配则导入空数据。
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;
//Esto lee los nombres de la tabla
/*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";
*/
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];
/*string[] nombres = 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>
它必须将任何 XML 文档转换为 SQL 上的表。如果它与属性的名称匹配。
【问题讨论】:
-
欢迎来到 Stack Overflow。请查看How to Ask,了解如何充分利用您的问题。您应该尝试将minimal reproducible example 放在一起以找出您的问题到底是什么。
-
这是因为我真的不知道该把代码放在哪里或修改什么。我知道它在代码中的 private void buttonCargar_Click(object sender, EventArgs e) 上。
-
@Marco Diez Barroso Zamudio 您能否将您的 XML(全部)发布到您上面的问题中(编辑您的问题并添加 XML,不要将 XML 放在此处的 cmets 中)
-
有XML,谢谢帮助。