一般xml文件用来保存初次配置内容,在项目搭建的时候 会创建一个xml 文件到启动文件中。
ps:这里注意了创建txt文件 要注意utf-8 编码 保存一下,修改后缀为.xml。
第一步读取xml文件:
string xmlPath = Application.StartupPath + "/config.xml";//获取 程序启动文件路径
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);//读取文件
XmlElement root = xml.DocumentElement;//获取根节点
//添加 节点
XmlElement node = xml.CreateElement("Student");
//节点属性 赋值
node.SetAttribute("Name", "小明");
node.SetAttribute("Age", "22");
node.SetAttribute("Sex", "男");
root.AppendChild(node);
xml.Save(xmlPath);//保存 xml文件
string xmlPath = Application.StartupPath + "/config.xml"; 这句代码后面加的 是自己 xml文件的名字。嘿!
最后别忘了 保存一下xml文件,要不操作就白作了。
然后看看对xml文件的操作:
string xmlPath = Application.StartupPath + "/config.xml";//获取 程序启动文件路径
//获取 节点内容
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);//读取文件地址
XmlElement root = xml.DocumentElement;//获取跟节点
XmlNode student = root.SelectSingleNode("Student");//读取节点
string cc = student.Attributes["Name"].Value;//读取节点 指定子节点
//修改节点内容
student.Attributes["Name"].Value = "小红";
Console.WriteLine(student.Attributes["Name"].Value);
//删除属性
XmlAttribute Sex = student.Attributes["Sex"];
student.Attributes.Remove(Sex);
//移除指定节点
//root.RemoveChild(student);
xml.Save(xmlPath);//保存xml文件
删除属性值 就是会把属性删掉,
删除节点属性值:
student.Attributes["Sex"].RemoveAll();
这样会直接把该属性 的值 设置为"",控制字符串。
追加节点属性:
//追加属性
XmlNode Score = xml.CreateNode(XmlNodeType.Attribute,"Score",null);
Score.Value = "44";
student.Attributes.SetNamedItem(Score);
