XML写入
private static void writeXml(){ using (XmlTextWriter xml = new XmlTextWriter(@"C:\Users\Dell\Desktop\boot.xml", Encoding.UTF8)) { try { xml.Formatting = Formatting.Indented; xml.WriteStartDocument(true); xml.WriteComment("学校的描述"); xml.WriteStartElement("school"); xml.WriteComment("学生的描述"); xml.WriteElementString("student", "学生"); xml.WriteComment("老师的描述"); xml.WriteElementString("teacher", "老师"); xml.WriteComment("校长的描述"); xml.WriteElementString("principal", "校长"); xml.WriteComment("编号的描述"); xml.WriteElementString("number", "123456"); xml.WriteComment("时间的描述"); xml.WriteElementString("Time", DateTime.Now.ToString()); xml.WriteEndElement(); xml.WriteEndDocument(); } catch (Exception ee) { Console.WriteLine(ee); } finally { xml.Flush(); xml.Close(); } }}
XML读取
private static string student { get; set; }private static string teacher { get; set; }private static string principal { get; set; }private static int number { get; set; }private static DateTime Time { get; set; }private static void readXml(){ string _xml_path = @"C:\Users\Dell\Desktop\boot.xml"; if (!File.Exists(_xml_path)) return; using (XmlTextReader xml = new XmlTextReader(_xml_path)) { try { while (xml.Read()) { if (xml.NodeType == XmlNodeType.EndElement && xml.Name == "school") break; if (xml.NodeType != XmlNodeType.Element) continue; switch (xml.Name) { case "student": student = xml.ReadString(); break; case "teacher": teacher = xml.ReadString(); break; case "principal": principal = xml.ReadString(); break; case "number": number = Convert.ToInt32(xml.ReadString()); break; case "Time": Time = Convert.ToDateTime(xml.ReadString()); break; } } } catch (Exception ee) { Console.WriteLine(ee); } finally { xml.Close(); } }}
控制台调用
static void Main(string[] args){ //writeXml(); //Console.WriteLine("完成"); readXml(); Console.WriteLine(student + teacher + principal + number + Time); Console.ReadKey();}
结果:
参考:、