01.using System;
02.using System.Data;
03.using System.Configuration;
04.using System.Collections;
05.using System.Web;
06.using System.Web.Security;
07.using System.Web.UI;
08.using System.Web.UI.WebControls;
09.using System.Web.UI.WebControls.WebParts;
10.using System.Web.UI.HtmlControls;
11.
12.using System.Xml;
13.
14.public partial class test_Default : System.Web.UI.Page
15.{
16. string xmlFile = System.Configuration.ConfigurationManager.AppSettings["xmlFile"];
17. XmlDocument XmlDoc = new XmlDocument();
18. protected void Page_Load(object sender, EventArgs e)
19. {
20. Bind();
21. }
22. private void Bind()
23. {
24. XmlDoc.Load(Server.MapPath("../" + xmlFile));//向上一级
25. this.showXml.InnerHtml = System.Web.HttpUtility.HtmlEncode(XmlDoc.InnerXml);
26. }
27. protected void XmlAdd(object sender, EventArgs e)
28. {
29. XmlNode objRootNode = XmlDoc.SelectSingleNode("//Root"); //声明XmlNode对象
30. XmlElement objChildNode = XmlDoc.CreateElement("Student"); //创建XmlElement对象
31. objChildNode.SetAttribute("id", "1");
32. objRootNode.AppendChild(objChildNode);
33. //
34. XmlElement objElement = XmlDoc.CreateElement("Name");//???结点和元素的区别?方法都一样.
35. objElement.InnerText = "tree1";
36. objChildNode.AppendChild(objElement);
37. //保存
38. XmlDoc.Save(Server.MapPath("../" + xmlFile));
39. }
40. protected void XmlDelete(object sender, EventArgs e)
41. {
42. string Node = "//Root/Student[Name='tree1']";//Xml是严格区分大小写的.
43. XmlDoc.SelectSingleNode(Node).ParentNode.RemoveChild(XmlDoc.SelectSingleNode(Node));
44. //保存
45. XmlDoc.Save(Server.MapPath("../" + xmlFile));
46. }
47. protected void XmlUpdate(object sender, EventArgs e)
48. {
49. //XmlDoc.SelectSingleNode("//Root/Student[Name='tree1']/Name").InnerText = "tree2";
50. XmlDoc.SelectSingleNode("//Root/Student[Name='tree1']").Attributes["id"].Value = "001";
51. //保存
52. XmlDoc.Save(Server.MapPath("../" + xmlFile));
53. }
54. protected void XmlQuery(object sender, EventArgs e)
55. {
56. XmlNodeList NodeList = XmlDoc.SelectNodes("//Root/Student");//查询全部的student节点
57. //循环遍历节点,查询是否存在该节点
58. for (int i = 0; i < NodeList.Count; i++)
59. {
60. Response.Write(NodeList[i].ChildNodes[0].InnerText);
61. }
62.
63. //查询单个节点,//表示全部匹配的元素./表示以此为根的子元素.javascript下的查询也是一样.
64. string XmlPathNode = "//Root/Student[Name='rock']/Photo";
65. Response.Write(XmlDoc.SelectSingleNode(XmlPathNode).InnerText);
66. }
67.}
c#操作XML

最新推荐文章于 2024-10-30 14:17:26 发布
