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

二次信任 提交于 2019-12-11 14:49:21

问题


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());
                }
            }
        }

回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/49808453/sql-server-return-select-statement-with-xml-datatype-and-convert-it-into-dataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!