且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Linq:使用C#.NET中的数据集加载XML文件

更新时间:2023-11-02 12:21:46

Use the following code







       public class authors
       {
           public string au_id { get; set; }
           public string au_lname { get; set; }
           public string au_fname { get; set; }
           public string phone { get; set; }
           public string address { get; set; }
           public string city { get; set; }
           public string state { get; set; }
           public string zip { get; set; }
           public bool contract { get; set; }
       }

private void btnLoad_Click(object sender, EventArgs e)
       {
           string filename = AppDomain.CurrentDomain.BaseDirectory + "employee.xml";//use your filepath
           var xmlresult = XDocument.Load(filename);

           var authorlist = from au in xmlresult.Descendants("Authors_Table").Descendants("authors")
                            select
                                new
                                {
                                    au_id = au.Element("au_id").Value,
                                    au_lname = au.Element("au_lname").Value,
                                    au_fname = au.Element("au_fname").Value,
                                    phone = au.Element("phone").Value,
                                    address = au.Element("address").Value,
                                    city = au.Element("city").Value,
                                    state = au.Element("state").Value,
                                    zip = au.Element("zip").Value,
                                    contract = au.Element("contract").Value

                                };

           List<authors> lstauthors = new List<authors>();

           foreach (var author in authorlist)
           {
               authors a_author = new authors();
               a_author.au_id = author.au_id;
               a_author.au_lname = author.au_lname;
               a_author.au_fname = author.au_fname;
               a_author.phone = author.phone;
               a_author.address = author.address;
               a_author.city = author.city;
               a_author.state = author.state;
               a_author.zip = author.zip;
               a_author.contract = (author.contract=="true")?true:false;
               lstauthors.Add(a_author);
           }
           dataGridView1.DataSource = lstauthors;
       }