使用 XML 中的列填充数据集 [英] Populate Dataset with columns from 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();
}
当我尝试运行此程序时,出现此错误:输入数组长于此表中的列数
When I try to run this I get this error: Input array is longer than the number of columns in this table
我猜我必须将列名添加到数据集或数据表中?我可以从 XML 中做到这一点吗?
I'm guessing i have to add column names to the dataset or datatable? Can I do that from XML?
EDIT 这是我使用 codeninja.sj 的方法运行时的响应
+---+-------------------------------------------------------------+----------------------+
| | id | updated |
+---+-------------------------------------------------------------+----------------------+
| 1 | http://services.odata.org/northwind/northwind.svc/Customers | 2016-02-15T20:21:21Z |
+---+-------------------------------------------------------------+----------------------
推荐答案
方法 1:您必须在创建源数据表时定义列名及其数据类型
Approach 1: You have to define column-names and its data-type while creating the source data-table
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 对象;并转换为与数据集相同的
Approach 2: Convert the API response as XML objects; and convert the same as data-set
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 响应重用相同的代码
Suggestion: Second approach is better than the first one; Because you can reuse the same code for different API responses
注意:根据您的 API 响应修改上述代码片段
Note: Modify the above code-snippets based on your API response
这篇关于使用 XML 中的列填充数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!