如何将XML加载到数据集中,然后操作数据集和重新绑定?
而不是使用XML文件,并绑定到列表框中,试试这个的:(source)
string myXMLfile = "C:\\MySchema.xml";
DataSet ds = new DataSet();
try
{
//reads file and loads data into dataset
ds.ReadXml(myXMLfile);
//set the listbox's datasource to the dataset
//note that if you have complex XML then you might need to set this to one of the datatables in the datset to get what you want
listBox1.DataSource = ds;
listBox1.DataBind();
}
catch (Exception ex)
{
//Handle error
}
让我们假设你的XML是相当简单的。于牵引添加到DataSet,你会怎么做:(source)
//if customers is the name of your table (have not seen your XML)
DataRow newCustomersRow = ds.Tables["Customers"].NewRow();
newCustomersRow["CustomerID"] = "ALFKI";
newCustomersRow["CompanyName"] = "Alfreds Futterkiste";
dataSet1.Tables["Customers"].Rows.Add(newCustomersRow);
下面是应上述工作的XML例子:
<Data>
<Customers>
<Customer>
<CustomerID>123</CustomerID>
<CompanyName>Name</CompanyName>
</Customer>
</Customers>
</Data>
我还没有编译或试图运行任何这个,但你应该得到一般的想法,并将其调整到你的代码中。
你能举个例子吗?数据源和数据集有什么区别? 当前我绑定了一个文件,然后我为listitems设置了绑定,以便框填满。 – internetmw 2010-07-28 00:32:39
数据源是您绑定到控件的数据源。在你的情况下,你正在使用xml文件作为数据源并将该数据绑定到列表框。数据源是一个表示数据表的类,如果你绑定到一个列表框,我想你的XML也代表了这个数据表。我会用一个例子更新我的文章。 – kniemczak 2010-07-28 01:41:04
而且这仍然可以用双向数据绑定工作,所以我可以更新源文件? – internetmw 2010-07-28 12:13:49