XML结构:
<?xml version="1.0" encoding="utf-8" ?>
- <bookstore>
- <book>
<title>C# premier</title>
<price>$15.0</price>
</book>
</bookstore>
前台主要代码:
<asp:GridView ID="gvBook" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="title" HeaderText="书名" />
<asp:BoundField DataField="price" HeaderText="价格" />
</Columns>
</asp:GridView>
<br />
书名:<asp:TextBox ID="tbTitle" runat="server"></asp:TextBox>
<br />
价格:<asp:TextBox ID="tbPrice" runat="server" ></asp:TextBox><br />
<asp:Button ID="btnAdd" runat="server" Text="添加" OnClick="btnAdd_Click" />
后台主要代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReadXML();
}
}
/// <summary>
/// 读XML
/// </summary>
public void ReadXML()
{
StreamReader sr = new StreamReader(Server.MapPath("xmlFile.xml"));
XmlDataDocument xdd = new XmlDataDocument();
xdd.DataSet.ReadXml(sr);
gvBook.DataSource = xdd.DataSet.Tables[0].DefaultView;
gvBook.DataBind();
sr.Close();
}
/// <summary>
/// 写XML
/// </summary>
public void WriteXML()
{
string title = tbTitle.Text;
string price = tbPrice.Text;
string xmlPath=Server.MapPath("xmlFile.xml");
XmlDocument xd = new XmlDocument();
xd.Load(xmlPath);
//构建根结点的子结点
XmlElement xe1=xd.CreateElement("title");
XmlText xt1=xd.CreateTextNode(title);
XmlElement xe2=xd.CreateElement("price");
XmlText xt2 = xd.CreateTextNode(price);
XmlNode xe=xd.CreateNode("element","book","");
xe.AppendChild(xe1);
xe.LastChild.AppendChild(xt1);
xe.AppendChild(xe2);
xe.LastChild.AppendChild(xt2);
//在根结点下追加一下新结点
XmlElement root = xd.DocumentElement;
root.AppendChild(xe);
xd.Save(xmlPath);
}
//向XML中添加记录
protected void btnAdd_Click(object sender, EventArgs e)
{
WriteXML();
ReadXML();
}
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛