【问题标题】:sproc using 'for xml' and then ExecuteXmlReader in C# -> "Data is Null. This method or property cannot be called on Null values."sproc 使用'for xml',然后在 C# 中使用 ExecuteXmlReader ->“数据为 Null。无法对 Null 值调用此方法或属性。”
【发布时间】:2010-11-25 14:22:05
【问题描述】:

我有一些代码:

XmlDocument doc = new XmlDocument();

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
            {
                SqlCommand command = connection.CreateCommand();

                command.CommandText = "sproc1";
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add(
                        new SqlParameter("@Param1",2));

                connection.Open();
                doc.Load(command.ExecuteXmlReader());
            }

从存储过程中加载一个 xml 文档。我明白了:

数据为空。不能对 Null 值调用此方法或属性。

当存储过程返回 null 时:

for xml raw, type, root('rows')

将表格结果转换成xml。

我怎样才能避免这种情况?是在我的 sql 代码中还是在 C# 中处理?

谢谢。

克里斯

【问题讨论】:

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


    【解决方案1】:

    到目前为止,我发现的最好的解决方法是在我的 sql 代码中使用它:

    DECLARE @XML XML;
    ...
    SELECT @XML = (select
    ...
    for xml raw, type, root('rows'))
    ...
    select case when @XML is not null then @XML else '<rows></rows>' end
    

    【讨论】:

    • 看起来不错的解决方法..返回默认值而不是 null 没有错。 :)
    【解决方案2】:

    好的..这段代码呢?

    connection.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(command);
    DataTable table = new DataTable();
    adapter.Fill(table);
    if (table.Rows.Count > 0)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlWriter writer = XmlTextWriter.Create(stream);
            table.WriteXml(writer);
            XmlReader reader = XmlReader.Create(stream);
            doc.Load(reader);
        }
    }
    

    【讨论】:

    • 我之前尝试过 - command.ExecuteXmlReader 抛出异常:{"Data is Null. This method or property cannot be called on Null values."}
    • @csetzkorn - 抱歉认为 Load 抛出了 execption。将尝试寻找替代方案。
    • 谢谢。我不得不给表起个名字,但得到: Root element is missing now
    • @csetzkorn - 抱歉.. 尝试多使用 DataAdapter/DataTable 的想法,有时间我会自己尝试..
    猜你喜欢
    • 2012-03-31
    • 2022-10-31
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多