Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

C# Convert xml to datatable

/// <summary>
        /// Convert XML to DataTable
        /// </summary>
        /// <param name="filePath">XML FIle Path</param>
        /// <returns>DataTable</returns>
        public DataTable Read(string filePath)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load(filePath);
                XmlNode parent = document.DocumentElement.ChildNodes.Cast<XmlNode>().ToList()[0];
                //Column 
                foreach (XmlNode column in parent)
                {
                    dt.Columns.Add(column.Name, typeof(string));
                }

                XmlElement root = document.DocumentElement;
                XmlNodeList childNodes = root?.ChildNodes;

                for (int i =0; i <= childNodes.Count - 1; i++)
                {
                    XmlNode child = document.DocumentElement.Cast<XmlNode>().ToList()[i];
                    List<string> rContent = new List<string>();
                    //rows
                    foreach (XmlNode item in child)
                    {
                        rContent.Add(item.InnerText);
                    }

                    dt.Rows.Add(rContent.ToArray());
                    rContent.Clear();
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
 
PREVIOUS NEXT
Tagged: #Convert #xml #datatable
ADD COMMENT
Topic
Name
8+5 =