Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:18:35 C#中XML应用实例实例
C#中XML应用实例实例|方法
XML应用实例 本实例主要使用C#结合XML技术实现一个简单的留言本。留言本主页及添加新留言页面分别如图1和图2所示。 程序开发步骤如下所示。 (1)新建一个网站,命名为31_04,其主页默认为Default.aspx。 (2)在该网站中添加一个list.xml文件、一个list.xsl文件和一个Default2.aspx页面,其中,list.xml文件用来存储留言内容,list.xsl文件用来对XML文件中的内容执行XSL样式转换,Default2.aspx页面用来作为添加新留言页面。 (3)程序主要代码。 存储留言内容的list.xml文件主要代码如下: 一个心情!! 2006-9-4 15:53:42 一个不再永远的话题,生活很累,但需要奋斗! 新的感悟!! 2006-9-5 16:29:50 每一天的工作,每一天的心情,每一天的事件,每一天的想法,每一天生活。 随心所意 2006-9-5 16:33:25 生活因心情的好坏而变得美丽与无奈,所以我们必须认真地做好生活中的每一件事情,因为只有这样才能让人有一种永远不能气馁的想法!! 对XML文件中内容执行XSL样式转换的list.xsl文件主要代码如下: 标题: 发表时间: Default.aspx页面中,首先定义一个XmlDocument类对象,并使用其Load方法加载指定的XML文件,然后定义一个XslTransform类对象,并使用该对象的Load方法加载指定的XSL文件,最后将Xml文件中的内容显示在Xml1控件中,并使用XslTransform类对象对XML文件中的内容进行样式转换。Default.aspx页面的Page_Load事件代码如下: protected void Page_Load(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("list.xml")); XslTransform trans = new XslTransform(); rans.Load(Server.MapPath("list.xsl")); Xml1.Document = doc; Xml1.Transform = trans; } Default2.aspx页面中,当单击【提交】按钮时,首先判断“留言标题”和“留言内容”文本框是否为空,如果为空,弹出提示信息;否则,调用XmlDocument对象的CreateElement方法生成新的元素,并使用AppendClild方法将新生成的元素添加到XML文件中。【提交】按钮的Click事件代码如下: protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text == "") { Response.Write(""); } else if (TextBox2.Text == "") { Response.Write(""); } else { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("list.xml")); XmlNode newNode1; XmlNode newNode2; newNode1 = doc.CreateElement("LIST"); newNode2 = doc.CreateElement("TITLE"); newNode2.InnerText = TextBox1.Text; newNode1.AppendChild(newNode2); newNode2 = doc.CreateElement("POSTTIME"); newNode2.InnerText = DateTime.Now.ToString(); newNode1.AppendChild(newNode2); newNode2 = doc.CreateElement("TEXT");
赞