读取XML文件并生成DataTable

前端之家收集整理的这篇文章主要介绍了读取XML文件并生成DataTable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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;
            }
        }
原文链接:https://www.f2er.com/xml/296459.html

猜你在找的XML相关文章