protected void addToXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("xml/XMLFile.xml"));
//创建新的节点
XmlElement newElement = xmlDoc.CreateElement("poems");
XmlElement elid = xmlDoc.CreateElement("id");
XmlElement elauthor = xmlDoc.CreateElement("author");
XmlElement elcontent = xmlDoc.CreateElement("content");
//XMLFile.xml文档中的形式
//
//
//
//
//
//
//为创建的节点传值
elid.InnerText = TextBox1.Text.Trim();
elauthor.InnerText = TextBox2.Text.Trim();
elcontent.InnerText = TextBox3.Text.Trim();
//把element添加到newElement下
newElement.AppendChild(elid);
newElement.AppendChild(elauthor);
newElement.AppendChild(elcontent);
//把newElement添加到xmlDoc下
xmlDoc.DocumentElement.AppendChild(newElement);//默认就是最后一条记录的后面
//如果要插到某条记录之后也可以用(加在第一条记录之后)
//xmlDoc.DocumentElement.InsertAfter(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//如果要插到某条记录之前也可以用(加在第一条记录之前)
//xmlDoc.DocumentElement.InsertBefore(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//存盘
xmlDoc.Save(Server.MapPath("xml.xml"));
}
}
//利用dataset插入xml数据 protected void btnAdd_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("xml/xMLFile.xml")); DataRow dr = ds.Tables[0].NewRow(); dr["author"] = TextBox1.Text.Trim(); dr["title"]=TextBox2.Text.Trim(); dr["content"] = TextBox3.Text.Trim(); ds.Tables[0].Rows.Add(dr); ds.WriteXml(Server.MapPath("xml/XMLFile.xml")); }
//这里是读取xml中的数据----我用的是datalist绑定----关键就是readxml()
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("xml/XMLFile.xml"));
if (ds.Tables.Count > 0)
{
DataList1.DataSource = ds.Tables[0].DefaultView;
DataList1.DataBind();
}
}
另一种方法:使用dataset.readxml
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("xml/XMLFile.xml"));
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
protected void searchFromXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("xml/XMLFile.xml"));
//按id精确查找
XmlNodeList xmlNodeList = xmlDoc.SelectNodes("smallfoolsRoot/poems[id='"+TextBox1.Text.Trim()+"']");
//模糊查找
//XmlNodeListxmlNodeList1=xmlDoc.SelectNodes("smallfoolsRoot/poems[contains(author,'"+TextBox1.Text.Trim()+"')]");
XmlNode xmlNode = xmlNodeList.Item(0);
Label1.Text = xmlNode["author"].InnerText;
Label2.Text = xmlNode["id"].InnerXml;
Label3.Text=xmlNode["content"].InnerText;
}
protected void feleteFromXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("xml/XMLFile.xml"));
XmlNodeList xmlNodeList = xmlDoc.SelectNodes("smallfoolsRoot/poems[id='"+TextBox1.Text.Trim()+"']");
XmlNode xmlNode = xmlNodeList.Item(0);
xmlNode.ParentNode.RemoveChild(xmlNode);
xmlDoc.Save(Server.MapPath("xml/XMLFile.xml"));
}