1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("guestbook.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;
// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("name", Server.HtmlEncode(txtName.Text));
myXmlElement.SetAttribute("email", Server.HtmlEncode(txtEmail.Text));
myXmlElement.SetAttribute("location", Server.HtmlEncode(txtLocation.Text));
myXmlElement.SetAttribute("date", DateTime.Now.ToString());
myXmlElement.InnerText = Server.HtmlEncode(txtComments.Text);
// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("guestbook.xml"));
// Re-bind data since the doc has been added to
BindData();
}
void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("guestbook.xml"));
DataSet myDataSet = new DataSet();
myDataSet.ReadXml(myXmlReader);
myXmlReader.Close();
Guestbook.DataSource = myDataSet.Tables[0];
Guestbook.DataBind();
}
} |