.Net操作Xml文件

219 阅读1分钟
string xmlPath = Application.StartupPath + "/config.xml";//获取程序启动文件路径

XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);//加载文件对象

XmlElement root = xml.DocumentElement;//获取根节点

XmlElement node = xml.CreateElement("NodeStudent");//创建节点

//节点属性赋值
node.SetAttribute("Name", "小明");
node.SetAttribute("Age", "22");
node.SetAttribute("Sex", "男");

root.AppendChild(node); //将新节点赋予根节点

XmlNode NodeStudent = 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);

xml.Save(xmlPath);//保存xml文件