簡體   English   中英

SQL Server返回具有XML數據類型的Select語句,並將其轉換為C#,ASP.Net中的DataSet

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

在數據庫表中,我具有XML數據類型的列名“ SectionDatatable”。 在我的C#代碼中,當我將數據庫連接到數據庫並查詢以獲取SectionDatatable時,該數據是數據庫中的XML格式UserDefinedSectionData。 我需要轉換XML數據類型中的'SectionDatatable'並將其轉換為DataSet,我該怎么做。 我已經停留了1天,以下是我的代碼。

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

這是將XML字符串轉換為DataSet的簡單示例。 此樣本還演示了如何處理DataSet所有表。

您需要用數據庫中的XML輸出替換此樣本中的XML字符串。 您可以根據訪問數據的需要更改代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM