How To Convert XMLNodeList To DataTable

After doing an XPath selection using .Net, using XmlDocument.SelectNodes(), it will return XMLNodeList class, sometimes we required to convert the XMLNodeList to Data Table for binding purposes. I couldn’t find a direct way, only way is using looping through the Nodes.

/// <summary>
    /// Converts an XMLNodelist object to data table.
    /// </summary>
    /// <param name="xmlNodeList">The XMLNodeList to convert to DataTable.</param>
    /// <param name="Columns">The columns required for the DataTable, using this parameter the
    /// data will be fetched from xmlnodelist.</param>
    /// <returns>DataTable with columns specified in the Columns parameter</returns>
    public DataTable XmlNodeListToDataTable(XmlNodeList xmlNodeList, string[] Columns)
    {
        //Creating the DataTable.
        using (DataTable dataTable = new DataTable("DataTable"))
        {
            //Adding data Table columns based on the columns parameter
            foreach (string column in Columns)
            {
                dataTable.Columns.Add(column);
            }
            //Adding rows with values.
            DataRow dataRow;
            foreach (XmlNode node in xmlNodeList)
            {
                dataRow = dataTable.NewRow();
                foreach (string column in Columns)
                {
                    dataRow[column] = node.SelectSingleNode(column).InnerText;
                }
                dataTable.Rows.Add(dataRow);
            }
            return dataTable;
        }
    }

You can also create the columns dynamically, but you need to check for duplicate Data Columns.

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>