0

我已经像这样创建了一个名为 SeedData.xml 的 xml 文件。

<Root>
    <User>
        <UserID>1</UserID>            
        <UserName>Admin</UserName>       
        <FirstName>Admin</FirstName>
        <LastName>Admin</LastName>
        <ShortName>Admin</ShortName>        
    </User>
</Root>

我已经像这样在 web.config 中包含了路径。

<appSettings>    
    <add key="myFilePath" value="D:\XmlSample\Common\SeedData.xml"/>
  </appSettings>

我需要将 xml 文件中的数据添加到数据库中。

我得到了xml的路径

string filePath = ConfigurationManager.AppSettings["myFilePath"];

但是如何从 xml 中提取值并保存在数据库中。我在 google 中搜索了很多,但我找不到解决方案。请帮忙

4

1 回答 1

1

XML 是一种基于标签的通用语言,非常容易跨应用程序传输和存储数据。.Net 技术是广泛支持的 XML 文件格式。.Net 框架为 XML 格式文件中的读取、写入和其他操作提供类。此外,ADO.NET 中的数据集使用 XML 格式作为其内部存储格式。

在这里,我们将使用 SQL 插入命令将 XML 文件的值插入到数据库表中。这里 Dataset 使用 XmlReader 来读取 XML 文件的内容。使用 XmlReader 定位 XML 文件并将 XmlReader 作为 Dataset 的参数传递。还使用连接字符串建立与数据库的连接。从 XML 文件中获取数据到 Dataset 后,我​​们可以遍历数据集值并使用 insert 命令将值添加到 Databse 中的表中。

尝试这个

 using System;
    using System.Data;
    using System.Windows.Forms;
    using System.Xml;
    using System.Data.SqlClient; 

    namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                string connetionString = null;
                SqlConnection connection;
                SqlCommand command ;
                SqlDataAdapter adpter = new SqlDataAdapter();
                DataSet ds = new DataSet();
                XmlReader xmlFile ;
                string sql = null;

                int ID = 0;
                string Name = null;
                double Price = 0;

                connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";

                connection = new SqlConnection(connetionString);

                xmlFile = XmlReader.Create("Xmlfile.xml", new XmlReaderSettings());
                ds.ReadXml(xmlFile);
                int i = 0;
                connection.Open();
                for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
                    Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
                    Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
                    sql = "insert into tablenamevalues(" + ID + ",'" + Name + "'," + Price + ")";
                    command = new SqlCommand(sql, connection);
                    adpter.InsertCommand = command;
                    adpter.InsertCommand.ExecuteNonQuery();
                }
                connection.Close();
                MessageBox.Show("Done .. ");
            }
        }
    }
于 2013-04-17T09:46:51.000 回答