Xml转化为DataTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/// <summary>
       /// XML转换为DataTable
       /// </summary>
       /// <param name="fileName">文件路径</param>
       /// <param name="tagName">节点路径</param>
       /// <returns>返回DataTable</returns>
       public static DataTable XmlToDataTable(string fileName, string tagName)
       {
           XmlDocument Xmldoc = new XmlDocument();
           Xmldoc.Load(fileName);
           XmlNodeList xlist = Xmldoc.SelectNodes(tagName);
           DataTable dt = new DataTable();
           DataRow dr;
           for (int i = 0; i < xlist.Count; i++)
           {
               dr = dt.NewRow();
               XmlElement xe = (XmlElement)xlist.Item(i);
               for (int j = 0; j < xe.Attributes.Count; j++)
               {
                   if (!dt.Columns.Contains("@" + xe.Attributes[j].Name))
                   {
                       dt.Columns.Add("@" + xe.Attributes[j].Name);
                   }
                   dr["@" + xe.Attributes[j].Name] = xe.Attributes[j].Value;
               }
               for (int j = 0; j < xe.ChildNodes.Count; j++)
               {
                   if (!dt.Columns.Contains(xe.ChildNodes.Item(j).Name))
                   {
                       dt.Columns.Add(xe.ChildNodes.Item(j).Name);
                   }
                   dr[xe.ChildNodes.Item(j).Name] = xe.ChildNodes.Item(j).InnerText;
               }
               dt.Rows.Add(dr);
           }
           return dt;
       }

  

posted @   逊老头  阅读(436)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示