【问题标题】:SQL Server return Select statement with XML datatype and convert it into DataSet in C#, ASP.NetSQL Server 以 XML 数据类型返回 Select 语句并将其转换为 C#、ASP.Net 中的 DataSet
【发布时间】:2018-04-13 02:32:54
【问题描述】:

在我的数据库表中,我有一个 XML 数据类型的列名“SectionDatatable”。在我的 C# 代码中,在我将数据库连接到我的数据库并进行查询以获取我的数据库中的 XML 格式 UserDefinedSectionData 之后。我需要将 XML Datatype 中的“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());
                }
            }
        }

【问题讨论】:

  • 为什么你使用 UserDefinedSectionData 作为表,虽然你提到它是一个列?什么是表名和列名?
  • @GaurangDave 很抱歉,我已经更正了。 SectionDatatable 是来自 UserDefinedSectionData 表的列
  • 在下面查看我的答案。希望对您有所帮助。

标签: c# asp.net sql-server xml sqlconnection


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多