1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml; 7 using System.IO; 8 9 namespace CreateXML 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 XmlDocument doc = new XmlDocument(); 16 17 18 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); 19 //添加了一个根节点 20 XmlElement Books = doc.CreateElement("Books"); 21 doc.AppendChild(Books); 22 //添加子节点 23 XmlElement Book = doc.CreateElement("Book"); 24 Books.AppendChild(Book); 25 XmlElement Name = doc.CreateElement("Name"); 26 Name.InnerText = "大话设计模式"; 27 Book.AppendChild(Name); 28 XmlElement Price = doc.CreateElement("Price"); 29 Price.InnerText = "26"; 30 Book.AppendChild(Price); 31 XmlElement Info = doc.CreateElement("Info"); 32 Info.InnerText = "26种设计模式详细解答"; 33 Book.AppendChild(Info); 34 //---添加另外一个子节点信息---------------------------------------------------- 35 Book = doc.CreateElement("Book"); 36 Books.AppendChild(Book); 37 Name = doc.CreateElement("Name"); 38 Name.InnerText = "JavaScript"; 39 Book.AppendChild(Name); 40 Price = doc.CreateElement("Price"); 41 Price.InnerText = "26"; 42 Book.AppendChild(Price); 43 Info = doc.CreateElement("Info"); 44 Info.InnerText = "JavaScript详细解答"; 45 Book.AppendChild(Info); 46 //---------------------------------------------------------------------------------------------- 47 doc.Save("MyBook.xml"); 48 Console.WriteLine("保存成功"); 49 //读取显示XML文档 50 doc.Load("MyBook.xml"); 51 //获取节点列表的集合 52 XmlNodeList xnl = doc.SelectNodes("/Books/Book"); 53 //循环遍历输出XML的innertext 54 foreach (XmlNode node in xnl) 55 { 56 Console.WriteLine(node.InnerText); 57 } 58 Console.ReadKey(); 59 } 60 } 61 }