[点晴永久免费OA]C#操作Xml文件
当前位置:点晴教程→点晴OA办公管理信息系统
→『 经验分享&问题答疑 』
using System; using System.Text; using System.Xml; class XmlOperate { private XmlDocument xmlDocument; private void CreateXmlFile(string filePath) { xmlDocument = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes"); XmlElement schoolElement = xmlDocument.CreateElement("school"); XmlElement studentElement = xmlDocument.CreateElement("student"); XmlElement nameElement = xmlDocument.CreateElement("name"); nameElement.InnerText = "张三"; studentElement.AppendChild(nameElement); XmlElement ageElement = xmlDocument.CreateElement("age"); ageElement.InnerText = "19"; studentElement.AppendChild(ageElement); XmlElement sexElement = xmlDocument.CreateElement("sex"); sexElement.InnerText = "男"; studentElement.AppendChild(ageElement); schoolElement.AppendChild(studentElement); xmlDocument.AppendChild(xmlDeclaration); xmlDocument.AppendChild(schoolElement); xmlDocument.Save(filePath); } private void ReadXmlFile(string fileName) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fileName); XmlNode Node = xmlDocument.DocumentElement; foreach (XmlNode item in Node) { Console.WriteLine("节点名称:" + item.Name); foreach (XmlNode studentNode in item) { switch (studentNode.Name) { case "name": Console.WriteLine("姓名:" + studentNode.InnerText); break; case "age": Console.WriteLine("年龄:" + studentNode.InnerText); break; case "sex": Console.WriteLine("性别:" + studentNode.InnerText); break; } } } } private void AddElement(XmlDocument xmlDocument) { XmlNode studentNode = xmlDocument.DocumentElement.SelectSingleNode("student"); XmlElement addressElement = xmlDocument.CreateElement("address"); addressElement.SetAttribute("city", "襄樊"); addressElement.InnerText = "樊城区19号"; studentNode.AppendChild(addressElement); } private void DeleteElement(XmlDocument xmlDocument) { XmlNode studentNode = xmlDocument.DocumentElement.SelectSingleNode("student"); foreach (XmlNode item in studentNode) { if (item.Name == "address") { studentNode.RemoveChild(item); } } } static void Main(string[] args) { string filePath = "c:\\school.xml"; XmlOperate xml = new XmlOperate(); //xml.CreateXmlFile(filePath); //xml.ReadXmlFile(filePath); xml.xmlDocument = new XmlDocument(); xml.xmlDocument.Load(filePath); //xml.AddElement(xml.xmlDocument); xml.DeleteElement(xml.xmlDocument); xml.xmlDocument.Save(filePath); } }
该文章在 2020/3/3 1:48:03 编辑过 |
关键字查询
相关文章
正在查询... |