需要使用Windows窗体(C#)将数据从XML导入SQL

时间:2016-04-20 21:48:03

标签: c# sql xml winforms

这是将数据从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上的表。如果它与属性的名称匹配。

1 个答案:

答案 0 :(得分:1)

好的,所以你想将XML数据导入到SQL表中的相应列(字段)......

在SQL Server上创建表和存储过程

/****** Object:  Table [dbo].[cliente]    Script Date: 21/04/2016 01:08:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cliente](
    [no_cliente] [nvarchar](max) NULL,
    [nombre] [nvarchar](max) NULL,
    [ap_paterno] [nvarchar](max) NULL,
    [ap_materno] [nvarchar](max) NULL,
    [calle] [nvarchar](max) NULL,
    [ciudad_cliente] [nvarchar](max) NULL,
    [password] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


/****** Object:  StoredProcedure [dbo].[SP_InsertXMLData]    Script Date: 21/04/2016 01:08:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_InsertXMLData] (@InputXML xml)
as
begin

    MERGE  cliente AS main
    USING (select Row.id.value('@no_cliente','[nvarchar](MAX)') as no_cliente, Row.id.value('@nombre','[nvarchar](MAX)') as nombre, Row.id.value('@ap_paterno','[nvarchar](MAX)') as ap_paterno, Row.id.value('@ap_materno','[nvarchar](MAX)') as ap_materno
            , Row.id.value('@calle','[nvarchar](MAX)') as calle, Row.id.value('@ciudad_cliente','[nvarchar](MAX)') as ciudad_cliente, Row.id.value('@password','[nvarchar](MAX)') as password
                from @InputXML.nodes('/Root/CSVDataRecord') as Row(id)) as stage
    ON main.password=stage.password
    WHEN MATCHED THEN
        UPDATE SET main.no_cliente=stage.no_cliente, main.nombre=stage.nombre, main.ap_paterno=stage.ap_paterno, main.ap_materno=stage.ap_materno , main.calle=stage.calle , main.ciudad_cliente=stage.ciudad_cliente, main.password=stage.password
    WHEN NOT MATCHED THEN 
        INSERT  (no_cliente, nombre, ap_paterno, ap_materno, calle, ciudad_cliente, password) 
        VALUES (stage.no_cliente, stage.nombre, stage.ap_paterno, stage.ap_materno, stage.calle, stage.ciudad_cliente, stage.password);
end

GO

这是代码

Usings

using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Xml.Linq;

代码...更新!!!

我修改了LINQ语句,以便在缺少元素(在XML中)时,新的XAttribute [发送到存储过程]默认为null ......

    static void Main(string[] args)
    {

        string strXML = File.ReadAllText("xml.xml");

        XDocument xmlsrcdoc = XDocument.Parse(strXML);

        using (SqlConnection connection = new SqlConnection("<Your connection string>"))
        {
            SqlCommand command = connection.CreateCommand();
            connection.Open();

            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText = "SP_InsertXMLData";
            XElement XMLData = new XElement("Root",
                from xml in xmlsrcdoc.Descendants("cliente").Descendants("cliente")
                select new XElement("CSVDataRecord",
                    new XAttribute("no_cliente", (string)xml.Element("no_cliente") ?? ""),
                    new XAttribute("nombre", (string)xml.Element("nombre") ?? ""),
                    new XAttribute("ap_paterno", (string)xml.Element("ap_paterno") ?? ""),
                    new XAttribute("ap_materno", (string)xml.Element("ap_materno") ?? ""),
                    new XAttribute("calle", (string)xml.Element("calle") ?? ""),
                    new XAttribute("ciudad_cliente", (string)xml.Element("ciudad_cliente") ?? ""),
                    new XAttribute("password", (string)xml.Element("password") ?? "")
                )
            );

            command.Parameters.Clear();
            command.Parameters.Add(new SqlParameter
            {
                ParameterName = "@InputXML",
                SqlDbType = SqlDbType.Xml,
                Value = new SqlXml(XMLData.CreateReader())
            });

            command.ExecuteNonQuery();
        }

    }

这是数据导入后SQL表的图片....

View of SQL Table after import

将XML保存到与.EXE相同的文件夹中的文件(xml.xml)中......希望有所帮助。