你好,我做了一份建议的demo,希望对你又帮助
一份Xml 文件,内容如下:
创建一个数据库 右边的数据是代码插入的。
Code
private void button1_Click(object sender, EventArgs e)
{
string xmlPath = @"XMLFile1.xml";
ListallStudents = new List ();
//1.加载XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
//2.读取 XML 里的数据
XmlNodeList nodeList = xmlDoc.SelectNodes("MyClass//Students//Student");
for (int i = 0; i < nodeList.Count; i++)
{
var stu = nodeList[i].ChildNodes;
StudentInfo student = new StudentInfo();
student.Name = stu[0].InnerText;
student.Address = stu[1].InnerText;
student.Phone = stu[2].InnerText;
allStudents.Add(student);
}
//3. 开始把数据写入数据库。
//需要学习的只是: SQL的增、删、改、查
string connPath = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Administrator\Documents\Visual Studio 2010\Projects\WinfomTest\WinfomTest\Test.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(connPath))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into Students values(@StudentName,@StudentAddress,@StudentPhone)";
for (int i = 0; i < allStudents.Count; i++)
{
cmd.Parameters.AddWithValue("StudentName", allStudents[i].Name);
cmd.Parameters.AddWithValue("StudentAddress", allStudents[i].Address);
cmd.Parameters.AddWithValue("StudentPhone", allStudents[i].Phone);
}
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("操作完成。");
}
祝你好运!加油 有问题 可以在沟通。。。