使用XML中的列填充数据集

时间:2016-02-13 00:35:35

标签: c# xml winforms web-services api

这是我到目前为止所做的:

public void CreateObject()
{
    const string ServerURl = "http://services.odata.org/northwind/northwind.svc/Customers";

    DataSet ds = new DataSet();
    DataTable sourcetable = new DataTable();

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ServerURl);

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    richTextBox1.AppendText(response.StatusDescription);
    Stream datastream = response.GetResponseStream();
    StreamReader reader2 = new StreamReader(datastream);

    using (StreamReader mySR = new StreamReader(datastream, Encoding.GetEncoding("iso-8859-1")))
    {
        XmlDocument lgnXml = new XmlDocument();
        lgnXml.Load(mySR);
        XmlNodeReader reader = new XmlNodeReader(lgnXml);

        ds.ReadXml(reader);

        foreach (DataTable table in ds.Tables)
        {
            foreach (DataRow dr in table.Rows)
            {
                sourcetable.Rows.Add(dr.ItemArray);
            }
        }

        dataGridView1.DataSource = sourcetable;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    CreateObject();
}

当我尝试运行时,我收到此错误:  输入数组长于此表中的列数

我猜我必须在数据集或数据表中添加列名?我可以从XML那样做吗?

编辑以下是使用codeninja.sj方法运行时的响应

+---+-------------------------------------------------------------+----------------------+
|   |                              id                             |       updated        |
+---+-------------------------------------------------------------+----------------------+
| 1 | http://services.odata.org/northwind/northwind.svc/Customers | 2016-02-15T20:21:21Z |
+---+-------------------------------------------------------------+----------------------

1 个答案:

答案 0 :(得分:4)

方法1:您必须在创建源数据表时定义列名及其数据类型

DataTable sourcetable = new DataTable();
sourcetable.Columns.Add("id", typeof(int));
sourcetable.Columns.Add("ColumnName1", typeof(string));
sourcetable.Columns.Add("ColumnName2", typeof(string));

方法2:将API响应转换为XML对象;并将其转换为数据集

string ServerURl = "http://localhost:53835/api/values";
DataSet ds = new DataSet();            
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ServerURl);
request.ContentType = "application/xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();            
var datastream = response.GetResponseStream();
XmlReader reader = XmlReader.Create(datastream);
ds.ReadXml(reader);
dataGridView1.DataSource = ds.Tables[0]; //ds.Tables["properties"] --> Specify your XML Node Name here

建议:第二种方法比第一种更好;因为您可以为不同的API响应重用相同的代码

注意: 根据您的API响应修改上述代码段