新手Xml读写教程
-
写入
/// <summary> /// 创建写入xml /// </summary> /// <param name="path"></param> /// <param name="filename"></param> private static void CreateXmlFile( string path,string filename) { XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlDeclaration xdDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xdDec); //创建根节点 XmlElement xeRoot = xmlDoc.CreateElement("sheet1_Info"); //给节点属性赋值 xeRoot.SetAttribute("version", "1.0"); xeRoot.SetAttribute("name", filename); xmlDoc.AppendChild(xeRoot); ////创建并添加<CreationInfo></CreationInfo>节点 XmlElement xeCreationInfo = xmlDoc.CreateElement("CreationInfo"); xeCreationInfo.SetAttribute("name", "创建信息"); ////创建并添加<CreatedBy></CreatedBy>节点 XmlElement xeCreatedBy = xmlDoc.CreateElement("CreatedBy"); xeCreatedBy.InnerText = "Tektronix Course Editor"; xeCreationInfo.AppendChild(xeCreatedBy); ////创建并添加<CreatedTime></CreatedTime>节点 XmlElement xeCreatedTime = xmlDoc.CreateElement("CreatedTime"); xeCreatedTime.InnerText = DateTime.Now.ToString(); xeCreationInfo.AppendChild(xeCreatedTime); ////创建并添加<SavedTime></SavedTime>节点 XmlElement xeSavedTime = xmlDoc.CreateElement("SavedTime"); xeSavedTime.InnerText = DateTime.Now.ToString(); xeCreationInfo.AppendChild(xeSavedTime); //悬着根节点,追加元素节点信息 XmlNode xmlSelect = xmlDoc.SelectSingleNode("sheet1_Info"); if (xmlSelect != null) { xmlSelect.AppendChild(xeCreationInfo); } //创建并添加<a></a>节点 xeRoot = xmlDoc.CreateElement("a"); if (xmlSelect != null) { xmlSelect.AppendChild(xeRoot); } //创建并添加<b></b>节点 xeRoot = xmlDoc.CreateElement("b"); if (xmlSelect != null) { xmlSelect.AppendChild(xeRoot); } //创建并添加<c></c>节点 xeRoot = xmlDoc.CreateElement("c"); if (xmlSelect != null) { xmlSelect.AppendChild(xeRoot); } //保存XML文档 try { xmlDoc.Save(path + "\\" + filename + ".xml");//也可以保存其他后缀名 } catch (Exception ep) { Console.WriteLine(ep.Message); } }
-
读取
/// <summary> /// 读取xml /// </summary> /// <param name="xmlfile"></param> public static void ReadXml(string xmlfile) { using (XmlReader reader = XmlReader.Create(xmlfile)) { while (reader.Read()) { var readNode = reader.Name; Console.WriteLine("当前读取节点:"+ readNode); if (readNode== "CreationInfo") { var attribute = reader.GetAttribute("name"); Console.WriteLine("CreationInfo的属性值已经找到:" + attribute); } } } }
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16609156.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。