1.XML是一种提供数据格式描述的标记语言。其自描述性使其非常适应于不同应用间的数据交换,而且这种交换不以预先定义的以组数据结构为前提!
eg:
<?xml version="1.0" encoding="utf-8"?> <root> <course_information> <courseName>操作系统</courseName> <courseTeacher>邹</courseTeacher> <coursePath>Database.aspx</coursePath> <courseAddTime>2006-7-1</courseAddTime> </course_information> <course_information> <courseName>数据库系统原理</courseName> <courseTeacher>胡</courseTeacher> <coursePath>Database.aspx</coursePath> <courseAddTime>2006-7-2</courseAddTime> </course_information> <course_information> <courseName>数据结构</courseName> <courseTeacher>李</courseTeacher> <coursePath>Database.aspx</coursePath> <courseAddTime>2006-7-30</courseAddTime> </course_information> </root>
2.编辑XML文档
先要把course_information.xml读入内存中,形成一棵DOM树,然后找到所要插入的父节点,添加一个新的
节点,添加一个新的节点,也就是XML文档的一个新的元素。最后把内存中的DOM树保存为一个XML文档。
eg:
添加新节点:
string st="Database.aspx"; DateTime date1=DateTime.Now; string date=date1.ToString("d"); XmlDocument xmlDoc=new XmlDocument(); xmlDoc.Load(file); XmlNode root=xmlDoc.SelectSingleNode("root");//select the root node; XmlElement course=xmlDoc.CreateElement("course_information"); XmlElement name=xmlDoc.CreateElement("courseName"); name.InnerText=this.TextBox1.Text; XmlElement teacher=xmlDoc.CreateElement("courseTeacher"); teacher.InnerText=this.TextBox2.Text; XmlElement path=xmlDoc.CreateElement("coursePath"); path.InnerText=st; XmlElement addTime=xmlDoc.CreateElement("courseAddTime"); addTime.InnerText=date; course.AppendChild(name); course.AppendChild(teacher); course.AppendChild(path); course.AppendChild(addTime); root.AppendChild(course); xmlDoc.Save(file); xmlDoc=null;
删除节点:
string filename=Server.MapPath(@".\XML\course_information.xml"); XmlDocument xmlDoc=new XmlDocument(); xmlDoc.Load(filename); string name=this.TextBox1.Text.ToString(); XmlNode oldNode=xmlDoc.SelectSingleNode("root/course_information[courseName='"+name+"']"); XmlNode root=xmlDoc.SelectSingleNode("root"); root.RemoveChild(oldNode); xmlDoc.Save(filename); xmlDoc=null; dt=op.ReadXml(filename); dv=dt.DefaultView; BindGrid();//绑定到DataGrid
|