XML格式如下:
<?xml version="1.0" encoding="gb2312"?>
<indexs>
<index>
<time>00:00:04:839</time>
<content>内容</content>
</index>
<index>
<time>00:00:12:707</time>
<content>内容</content>
</index>
</indexs>
代码如下:
View Code
1 /// <summary> 2 /// 从XML文件获取数据 3 /// </summary> 4 /// <param name="dataGridView">数据显示控件</param> 5 /// <param name="fileName">文件名</param> 6 /// <param name="filePath">路径</param> 7 public void LoadIndexInfo(DataGridView dataGridView, string fileName, string filePath) 8 { 9 //获取xml文件名 10 string xmlName = filePath.Substring(0, filePath.LastIndexOf('\\')) + "\\" + fileName.Substring(0, fileName.LastIndexOf('.')) + ".xml"; 11 12 try 13 { 14 //节点标题 15 string[] header = { "时间", "内容" }; 16 XmlDocument xmlDoc = new XmlDocument(); 17 xmlDoc.Load(xmlName); 18 //根节点 19 XmlElement root = xmlDoc.DocumentElement; 20 //index元素节点 21 XmlElement index = (XmlElement)root.SelectSingleNode("index"); 22 23 if (index == null) 24 { 25 while (dataGridView.Rows.Count > 0) 26 { 27 dataGridView.Rows.RemoveAt(0); 28 } 29 } 30 31 //index节点下的节点列表 32 XmlNodeList nodeList = index.ChildNodes; 33 //设置头部 34 DataTable dt = new DataTable(); 35 36 //获取列名 37 for (int i = 0; i < header.Length; i++) 38 { 39 DataColumn dc = new DataColumn(header[i]); 40 dt.Columns.Add(dc); 41 } 42 XmlNodeList indexs = root.GetElementsByTagName("index"); 43 for (int k = 0; k < indexs.Count; k++) 44 { 45 DataRow dr = dt.NewRow(); 46 for (int i = 0; i < nodeList.Count; i++) 47 { 48 dr[i] = indexs[k].ChildNodes[i].InnerText; 49 } 50 dt.Rows.Add(dr); 51 } 52 dt.DefaultView.Sort = dt.Columns["时间"] + " ASC"; 53 } 54 catch(Exception e) 55 { 56 throw e; 57 } 58 }