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. namespace _5_追击XML
    9. {
    10. class Program
    11. {
    12. static void Main(string[] args)
    13. {
    14. //追加XML文档
    15. XmlDocument doc = new XmlDocument();
    16. XmlElement books;
    17. if (File.Exists("Books.xml"))
    18. {
    19. //如果文件存在 加载XML
    20. doc.Load("Books.xml");
    21. //获得文件的根节点
    22. books = doc.DocumentElement;
    23. }
    24. else
    25. {
    26. //如果文件不存在
    27. //创建第一行
    28. XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    29. doc.AppendChild(dec);
    30. //创建跟节点
    31. books = doc.CreateElement("Books");
    32. doc.AppendChild(books);
    33. }
    34. //5、给根节点Books创建子节点
    35. XmlElement book1 = doc.CreateElement("Book");
    36. //将book添加到根节点
    37. books.AppendChild(book1);
    38. //6、给Book1添加子节点
    39. XmlElement name1 = doc.CreateElement("Name");
    40. name1.InnerText = "c#开发大全";
    41. book1.AppendChild(name1);
    42. XmlElement price1 = doc.CreateElement("Price");
    43. price1.InnerText = "110";
    44. book1.AppendChild(price1);
    45. XmlElement des1 = doc.CreateElement("Des");
    46. des1.InnerText = "看不懂";
    47. book1.AppendChild(des1);
    48. doc.Save("Books.xml");
    49. Console.WriteLine("保存成功");
    50. Console.ReadKey();
    51. }
    52. }
    53. }
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <Books>
    3. <Book>
    4. <Name>金瓶梅</Name>
    5. <Price>10</Price>
    6. <Des>好看</Des>
    7. </Book>
    8. <Book>
    9. <Name>金瓶梅</Name>
    10. <Price>10</Price>
    11. <Des>好看</Des>
    12. </Book>
    13. <Book>
    14. <Name>c#开发大全</Name>
    15. <Price>110</Price>
    16. <Des>看不懂</Des>
    17. </Book>
    18. </Books>