たとえば、BookDetails を含む xml ファイルがあり、それを GridView フォームに表示しました。ここで、GridView に追加、編集、削除のオプションを提供したいと考えています。SQLデータソースからDataBindingを使用するときにgridviewに追加、編集、削除オプションを与える方法を知っていますが、ここでは既存のxmlファイルにデータを保存する必要があります。
データを含む XML ファイル:
<books>
<book>
<title>CLR via C#</title>
<isbn>0735667454</isbn>
<author>Jeffrey Richter</author>
</book>
<book>
<title>Pro C# 5.0 and the .NET 4.5 Framework</title>
<isbn>1430242337</isbn>
<author>Andrew Troelsen</author>
</book>
<book>
<title>Building Windows 8 Apps with C# and XAML</title>
<isbn>0321822161</isbn>
<author>Jeremy Likness</author>
</book>
</books>
ASP.NET コード
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Book Store</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvBooks" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
C# コード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindXml();
}
private void bindXml()
{
//Create a DataSet
DataSet ds = new DataSet();
//Load the XML data into the DataSet
ds.ReadXml(Server.MapPath("books.xml"));
//Bind the DataSet to the GridView control
gvBooks.DataSource = ds;
gvBooks.DataBind();
}
}