Search code examples
c#asp.netsql-serverxmlsqlconnection

SQL Server return Select statement with XML datatype and convert it into DataSet in C#, ASP.Net


In my database table, I have a column name 'SectionDatatable' which are in XML datatype. In my C# code, after I have connection to database to my database and I make a query to get SectionDatatablewhich is XML format in my database, UserDefinedSectionData. I need to convert the 'SectionDatatable' in XML Datatype and convert it into DataSet, how can I do it. I have stuck for 1 day, the following is my code.

        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @"CPX-XSYPQKSA91D\SQLEXPRESS";
        csb.InitialCatalog = "DNN_Database";
        csb.IntegratedSecurity = true;

        string connString = csb.ToString();

        string queryString = "select * FROM UserDefinedSectionData WHERE SectionDataTabId = @tabId";

        using (SqlConnection connection = new SqlConnection(connString))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = queryString;
            command.Parameters.Add(new SqlParameter("tabId", tabId));
            connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    string sectionData= reader["SectionDatatable"].ToString();
                    int moduleId = Int32.Parse(reader["SectionDataModuleId"].ToString());
                }
            }
        }

Solution

  • This is the simple example of converting XML string to DataSet. This sample also demonstrates processing all tables in DataSet.

    You need to replace XML string in this sample with your XML output from database. You can change code as per you need to access data.

    string RESULT_OF_SectionDatatable = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
    var xmlReader = XmlReader.Create(new StringReader(RESULT_OF_SectionDatatable));
    
    DataSet ds = new DataSet();
    ds.ReadXml(xmlReader);
    
    foreach (DataTable table in ds.Tables)
    {
        Console.WriteLine(table);
        Console.WriteLine();
    
        foreach (var row in table.AsEnumerable())
        {
            for (int i = 0; i < table.Columns.Count; ++i)
            {
                Console.WriteLine(table.Columns[i].ColumnName +"\t" + row[i]);
            }
            Console.WriteLine();
        }
    }