2016-02-13 217 views
2

這裏列是我到目前爲止有:填充數據集從XML

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 | 
+---+-------------------------------------------------------------+---------------------- 

回答

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:轉換爲XML對象的API響應;並轉換成相同的數據集

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響應

+0

我嘗試了第二種方法,我只在DataGridView有一行回 – Sewder

+0

@Sewder,可以分享你的API響應嗎? –

+0

我將它添加到問題 – Sewder