- 最近做个程序需要用到保存数据,由于太小想到了用xml,研究下,写了个简单的方法贴出来看看
- privatevoidgettime()
- {
- //实例化xml
- XmlDocumentdocument=newXmlDocument();
- //加载xml,有同学说可以用xmlLoad,我试了可以,但是好有时候会报错,建议用load用过的都懂的
- //发布后的项目网页等等建议用document.Load(Server.MapPath("settime.xml"));具体就不多说了
- document.Load("settime.xml");
- //////////*******下面开始循环读取xml文件信息********////////////////
- foreach(XmlNodenodeindocument.ChildNodes)
- {
- //获取第一子节点
- if(node.Name=="aa")
- {
- //在获取这一节点内的所有子节点:ChildNodes子节点
- foreach(XmlNodenode1innode.ChildNodes)
- {
- //一一判断节点名称,对应的节点插入不同的数据
- if(node1.Name=="A")
- {
- textBox1.Text=node1.InnerText;
- }
- if(node1.Name=="B")
- {
- textBox2.Text=node1.InnerText;
- }
- if(node1.Name=="C")
- {
- textBox3.Text=node1.InnerText;
- }
- if(node1.Name=="D")
- {
- textBox4.Text=node1.InnerText;
- }
- if(node1.Name=="E")
- {
- textBox5.Text=node1.InnerText;
- }
- if(node1.Name=="F")
- {
- textBox6.Text=node1.InnerText;
- }
- }
- }
- }
- //记得保存啊,有同学老是忘记保存,还怪我代码问题,无辜了
- document.Save("settime.xml");
- }
- 读取写入
- privatevoidsettime()
- {
- XmlDocumentdocument=newXmlDocument();
- document.Load("settime.xml");
- foreach(XmlNodenodeindocument.ChildNodes)
- {
- //获取第一子节点
- if(node.Name=="aa")
- {
- //在获取这一节点内的所有子节点:ChildNodes子节点
- foreach(XmlNodenode1innode.ChildNodes)
- {
- if(node1.Name=="A")
- {
- node1.InnerText=textBox1.Text.Trim();
- }
- if(node1.Name=="B")
- {
- node1.InnerText=textBox2.Text.Trim();
- }
- if(node1.Name=="C")
- {
- node1.InnerText=textBox3.Text.Trim();
- }
- if(node1.Name=="D")
- {
- node1.InnerText=textBox4.Text.Trim();
- }
- if(node1.Name=="E")
- {
- node1.InnerText=textBox5.Text.Trim();
- }
- if(node1.Name=="F")
- {
- node1.InnerText=textBox6.Text.Trim();
- }
- }
- }
- }
- document.Save("settime.xml");
- }
- 示例
- <?xmlversion="1.0"encoding="utf-8"?>
- <!--第一节点-->
- <aa>
- <!--第一节点的子节点-->
- <A>
- <!--InnerText值foreach循环读取和赋值-->
- 09:00:00
- </A>
- <B>
- 12:00:00
- </B>
- <C>
- 14:30:00
- </C>
- <D>
- 18:00:00
- </D>
- <E>
- 14:00:00
- </E>
- <F>
- 17:30:00
- </F>
- </aa>
- 有什么问题可以来到我发的个人博客留言,我的博文地址 http://www.541ta.com/post/16.html