『C#基础』XML文件的读与写

几点说明

  1. 由于手头正好有一个程序上有现成的读写XML的代码,所以就近研究一下~
  2. 代码的版本是.NET 1.1 的~
  3. 使用到的命名空间:
    1. System.Xml
  4. 读取XML步骤
    1. 实例化一个XmlDocument对象
    2. 使用XmlDocument.Load(文件目录+文件名称)方法将XML文件读到内存中
    3. 使用foreach迭代与XmlElement对象来遍历已经读到内存中的XmlDocument.DocumentElement
    4. 使用XmlElement[Key].InnerText来读取对应Key元素的值
  5. 写入XML步骤
    1. 将要写入的XML文件读入内存
    2. 使用迭代来检查一下XML中是否有想要写入的节点
    3. 如果有,则使用XmlElement[Key].InnerText = Value
    4. 如果没有,则使用XmlElement Key = XmlDocument.CreateElement("Key")来创建一个Xml节点
      1. 使用XmlElement Child_Key = XmlDocument.CreateElement("Child_Key")再创建一个Xml节点
      2. 使用Child_Key.InnerText = "Value";来赋节点值
      3. 使用Key.AppendChild(Child_Key)来给对应的Key添加一个子节点
    5. 使用System.IO.FileInfo info = new System.IO.FileInfo(路径+Xml文件名)来获取文件信息
      1. 使用info.Attributes来获取文件的属性
      2. 使用info.Attributes == System.IO.FileAttributes.ReadOnly来确定文件是否是只读
      3. 如果是只读,则可以会用System.IO.FileAttributes.Normal来恢复文件初始属性,以解掉Xml文件的只读属性
    6. 使用XmlDocument.Save(路径+Xml文件名);来将之前写入数据的XML保存

样例界面

image

image

image

参考代码

Data Binding Example - CS

原文地址:https://www.cnblogs.com/sitemanager/p/2360259.html