将XML文件读入数据库

时间:2015-10-07 16:00:50

标签: c# xml database

我在将XML文件读入数据库时​​出现问题。我在VS项目中获得了我的HD数据库。我不知道如何将XML文件中的值放入我的数据库中。我几乎掌握了它,但我错过了一些东西。因此,如果有人能够解释我在代码中遗漏的内容,我会很感激。

我编写XML文件的代码:

try
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Planeter.mdf;Integrated Security=True");

    StreamWriter outputFile = File.CreateText("min_XML2.xml");

    SqlDataAdapter adapter = new SqlDataAdapter("select * from Planet", con);
    DataSet ds = new DataSet("Planeter");
    adapter.Fill(ds, "Planet");
    ds.WriteXml(outputFile);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

到目前为止我的代码用于读取XML文件:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Planeter.mdf;Integrated Security=True");
con.Open();

StreamReader inputFile = File.OpenText("min_XML2.xml");
DataSet ds = new DataSet();
ds.ReadXml(inputFile);

DataTable dt = ds.Tables["Planet"];
dt.Rows.Add("value1","value2", "value3?"); //??Adding row?? Stuck...

con.Close();

dt.Rows.Add我被卡住了。我想将XML文件中的每个值都放入我的数据库中。我得到了" teqnique"在网站上写XML文件,所以我不知道它是否最好。但我真的不明白最后一行代码中的值应该做什么或它们是什么。我的数据库中的列名称为NamnDygnslangdArslangd

这就是我的XML文件的样子:



<?xml version="1.0"?>
<Planeter>
    <Planet>
        <Namn>asd</Namn>
        <Dygnslangd>33</Dygnslangd>
        <Arslangd>33</Arslangd>
    </Planet>
    <Planet>
        <Namn>Jorden</Namn>
        <Dygnslangd>24</Dygnslangd>
        <Arslangd>365</Arslangd>
    </Planet>
    <Planet>
        <Namn>Mars</Namn>
        <Dygnslangd>24</Dygnslangd>
        <Arslangd>687</Arslangd>
    </Planet>
    <Planet>
        <Namn>Merkurius</Namn>
        <Dygnslangd>58</Dygnslangd>
        <Arslangd>88</Arslangd>
    </Planet>
    <Planet>
        <Namn>Venus</Namn>
        <Dygnslangd>244</Dygnslangd>
        <Arslangd>224</Arslangd>
    </Planet>
</Planeter>
&#13;
&#13;
&#13;

最诚挚的问候。

1 个答案:

答案 0 :(得分:2)

您应该可以使用以下方法执行此操作:

  • XML反序列化,将XML文件读入包含行星的内存中结构
  • 一个简单,整齐,参数化的ADO.NET SqlCommand,每个行星执行一次,并将数据插入SQL Server数据库表。

请在此处试用此代码:

// C# classes for the XML structure
using System.Xml.Serialization;

namespace PlaneterXml
{
    [XmlRoot(Namespace = "", IsNullable = false)]
    public partial class Planeter
    {
        private Planet[] itemsField;

        [XmlElement("Planet", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public Planet[] Items
        {
            get { return this.itemsField; }
            set { this.itemsField = value; }
        }
    }

    [XmlType(AnonymousType = true)]
    public partial class Planet
    {
        public string Namn { get; set; }
        public int Dygnslangd { get; set; }
        public int Arslangd { get; set; }
    }
}

// C# code to read the XML (deserialize it) and then insert
// the planets read from the file into the database table
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace PlaneterXml
{
    class Program
    {
        static void Main(string[] args)
        {
            // adapt to *your* file name - possibly put this in a 
            // configuration file, or pick the file interactively 
            string fileName = @"C:\tmp\planeter.xml";

            Planeter allPlanets = null;

            using (FileStream fstm = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                // create XML serializer for the "Planeter" type
                XmlSerializer planetSerializer = new XmlSerializer(typeof(Planeter));

                // deserialize the XML into a "Planeter" object    
                allPlanets = planetSerializer.Deserialize(fstm) as Planeter;
            }

            // Define connection string and insert query
            // connection string would typically come from a config file
            string connectionString = @"server=.;database=test;integrated security=SSPI;";
            string insertQuery = @"INSERT INTO dbo.Planets(Namn, Dygnslangd, Arslangd) VALUES(@Namn, @Dygnslangd, @Arslangd);";

            // create SqlConnection and SqlCommand to insert
            using (SqlConnection conn  =new SqlConnection(connectionString))
            using (SqlCommand insertCmd = new SqlCommand(insertQuery, conn))
            {
                // define parameters
                insertCmd.Parameters.Add("@Namn", SqlDbType.VarChar, 100);
                insertCmd.Parameters.Add("@Dygnslangd", SqlDbType.Int);
                insertCmd.Parameters.Add("@Arslangd", SqlDbType.Int);

                // open connection, loop over planets, execute query
                conn.Open();

                foreach (Planet p in allPlanets.Items)
                {
                    // set parameter values
                    insertCmd.Parameters["@Namn"].Value = p.Namn;
                    insertCmd.Parameters["@Dygnslangd"].Value = p.Dygnslangd;
                    insertCmd.Parameters["@Arslangd"].Value = p.Arslangd;

                    insertCmd.ExecuteNonQuery();
                }

                // close connection
                conn.Close();
            }
        }
    }
}