【问题标题】:There was an error generating the XML document in C#在 C# 中生成 XML 文档时出错
【发布时间】:2017-10-16 10:58:41
【问题描述】:

我正在尝试使用此代码,但它给了我错误,我只想使用数据表而不是数据集

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public DataTable NameArray()
        {
            DataTable imageTable = new DataTable("gcm");
            // imageTable.Columns.Add("image_name", typeof(String));
            imageTable.Columns.Add("username", typeof(String));
            imageTable.Columns.Add("gcmkey", typeof(String));
            if (con.State.ToString() == "Closed")
            {
                con.Open();
            }
            string query = "SELECT * from gcm";
            SqlCommand command = new SqlCommand(query, con);

            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    imageTable.Rows.Add(reader["username"],reader["gcmkey"]);
                }
            }
          this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(json.Serialize(new { PersonalProfile = reader }));
            reader.Close();
            con.Close();
            return imageTable; }

错误显示如下:

 This page contains the following errors:

error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.

那么,如何从数据表中获取数据,而不是从数据集中获取数据?

【问题讨论】:

  • 为什么不用使用SQlDataAdapter来填充数据表而不是SqlDataReader呢?填写数据表是一条指令。代码看起来应该可以工作。所以要么阅读器代码有错误,要么查询没有返回任何行。这是您收到文档为空的错误消息的唯一两个原因。

标签: c# sql asp.net json xml


【解决方案1】:

您需要为数据表命名 您应该为数据表设置名称的错误状态。请这样做。 例如

dt.TableName = "myTable";
dt.WriteXml(@"path", true);

【讨论】:

    【解决方案2】:

    你读过异常吗?

    无法序列化 DataTable。数据表名称未设置。

    给你的桌子起个名字:

    DataTable imageTable = new DataTable("tableName");
    

    【讨论】:

    • 现在它告诉我error on line 1 at column 1: Document is empty
    • 嗯,这应该是另一个问题,但我想这是因为 Response.Write 你正在做。这是为什么?您返回 DataTable,没有理由也序列化阅读器
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多