标签:
本文主要讲将XML数据读取到数据库中,和从读取数据库中数据写入XML,数据库使用MySql
首先脑补下XML的知识:
1 static void Main(string[] args) 2 { 3 DataTable table = GetDataTable(); 4 List<Student> stuList = TableToList(table); 5 XDocument xdoc = new XDocument(); 6 XElement root = new XElement("Person"); 7 xdoc.Add(root);//添加根节点 8 foreach (Student stu in stuList) 9 { 10 XElement stuEle = new XElement("Student"); 11 stuEle.SetAttributeValue("stuId",stu.Student_Id.ToString());//设置属性 12 stuEle.SetElementValue("name",stu.Name);//设置子节点和值 13 stuEle.SetElementValue("class", stu.Class); 14 stuEle.SetElementValue("gender", stu.Gender); 15 root.Add(stuEle); 16 } 17 xdoc.Save("1.xml"); 18 Console.WriteLine("数据库写入完毕"); 19 Console.ReadKey(); 20 } 21 /// <summary> 22 /// 读取数据库表数据 23 /// </summary> 24 /// <returns></returns> 25 public static DataTable GetDataTable() 26 { 27 string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; 28 DataSet ds= MySqlHelper.ExecuteDataset(connstr,"select * from student"); 29 return ds.Tables[0]; 30 } 31 /// <summary> 32 /// 将行转换为list 33 /// </summary> 34 /// <param name="table"></param> 35 /// <returns></returns> 36 public static List<Student> TableToList(DataTable table) 37 { 38 List<Student> list = new List<Student>(); 39 for (int i = 0; i < table.Rows.Count; i++) 40 { 41 Student stu = new Student(); 42 DataRow row=table.Rows[i]; 43 stu.Class = row["Class"].ToString(); 44 stu.Gender = row["Gender"].ToString(); 45 stu.Name = row["Name"].ToString(); 46 stu.Student_Id = Convert.ToInt32(row["Student_Id"]); 47 list.Add(stu); 48 } 49 return list; 50 }
读取xml数据插入到数据库
主要用到的方法item.Attribute("Xname").value--获取属性的值 item.Element("Xname").value--获取子节点的值
1 string connstr = "server=localhost;database=test;user id=root;password=123"; 2 XDocument xdoc = XDocument.Load(@"F:\tmp\1.xml"); 3 XElement root = xdoc.Root; 4 foreach (XElement item in root.Elements()) 5 { 6 //Console.WriteLine(item.Element("name").Value); 7 //Console.WriteLine(item.Element("class").Value); 8 //Console.WriteLine(item.Element("gender").Value); 9 string sql = "insert into student(Student_Id,Name,Class,Gender)values(@Student_Id,@Name,@Class,@Gender)"; 10 MySqlParameter[] ps = { 11 new MySqlParameter("@Student_Id",item.Attribute("stuId").Value),//读取属性值 12 new MySqlParameter("@Name",item.Element("name").Value),//读取子节点值 13 new MySqlParameter("@Class",item.Element("class").Value), 14 new MySqlParameter("@Gender",item.Element("gender").Value) 15 }; 16 MySqlHelper.ExecuteNonQuery(connstr, sql, ps);//插入数据库 17 } 18 Console.WriteLine("ok"); 19 Console.ReadKey();
标签:
原文地址:http://www.cnblogs.com/lucyliang/p/4987608.html