读取XML文件并生成DataTable

时间:2021-04-06 12:04:23

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>

代码如下:

/// <summary>
/// 从XML文件获取数据
/// </summary>
/// <param name="dataGridView">数据显示控件</param>
/// <param name="fileName">文件名</param>
/// <param name="filePath">路径</param>
public void LoadIndexInfo(DataGridView dataGridView, string fileName, string filePath)
{
//获取xml文件名
string xmlName = filePath.Substring(0, filePath.LastIndexOf('\\')) + "\\" + fileName.Substring(0, fileName.LastIndexOf('.')) + ".xml";

try
{
//节点标题
string[] header = { "时间", "内容" };
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
//根节点
XmlElement root = xmlDoc.DocumentElement;
//index元素节点
XmlElement index = (XmlElement)root.SelectSingleNode("index");

if (index == null)
{
while (dataGridView.Rows.Count > 0)
{
dataGridView.Rows.RemoveAt(0);
}
}

//index节点下的节点列表
XmlNodeList nodeList = index.ChildNodes;
//设置头部
DataTable dt = new DataTable();

//获取列名
for (int i = 0; i < header.Length; i++)
{
DataColumn dc = new DataColumn(header[i]);
dt.Columns.Add(dc);
}
XmlNodeList indexs = root.GetElementsByTagName("index");
for (int k = 0; k < indexs.Count; k++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < nodeList.Count; i++)
{
dr[i] = indexs[k].ChildNodes[i].InnerText;
}
dt.Rows.Add(dr);
}
dt.DefaultView.Sort = dt.Columns["时间"] + " ASC";
}
catch(Exception e)
{
throw e;
}
}