using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace XML { class Program { static void Main(string[] args) { //创建一个泛型集合 List<students> list = new List<students>(); //读取数据 DataTable tb = MySqlHelper.ExecuteQuery("select * from t_student"); if (tb.Rows.Count > 0) { //有数据 foreach (DataRow r in tb.Rows) { students stu = RowToStudent(r); if (stu != null) { list.Add(stu); } } } XDocument xdoc = new XDocument(); //XML根节点 XElement root = new XElement("Person"); //遍历集合 for (int i = 0; i < list.Count; i++) { students stu = list[i]; XElement student = new XElement("Student"); student.SetAttributeValue("StuId",stu.ID.ToString()); student.SetElementValue("StuName", stu.Name); student.SetElementValue("StuAge", stu.Age); student.SetElementValue("StuGender", stu.Gender); root.Add(student); } xdoc.Add(root); //保存 xdoc.Save(@"C:\Users\Administrator\Desktop\xml\stu.xml"); Console.WriteLine("数据全部导出!"); Console.ReadKey(); } public static students RowToStudent(DataRow dr) { //为students对象字段赋值 students stu = new students(); stu.ID = Convert.ToInt32( dr["id"]); stu.Name = dr["name"].ToString(); stu.Age = Convert.ToInt32(dr["age"]); stu.Gender = dr["gender"].ToString(); return stu; } } }
时间: 2024-10-15 12:31:08