码迷,mamicode.com
首页 > 数据库 > 详细

C# 数据库数据导出XML

时间:2015-09-11 20:37:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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;
            
        }
    }
}

 

C# 数据库数据导出XML

标签:

原文地址:http://www.cnblogs.com/phpweige/p/4801946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!