[點(diǎn)晴永久免費(fèi)OA]C#操作Xml文件
當(dāng)前位置:點(diǎn)晴教程→點(diǎn)晴OA辦公管理信息系統(tǒng)
→『 經(jīng)驗分享&問題答疑 』
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("節(jié)點(diǎn)名稱:" + 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 = "樊城區(qū)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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |