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. namespace _03创建XML
    8. {
    9. class Program
    10. {
    11. static void Main(string[] args)
    12. {
    13. //通过代码来创建XML文档
    14. //1、引用命名空间
    15. //2、创建XML文档对象
    16. XmlDocument doc = new XmlDocument();
    17. //3、创建第一个行描述信息,并且添加到doc文档中
    18. XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    19. doc.AppendChild(dec);
    20. //4、创建根节点
    21. XmlElement books = doc.CreateElement("Books");
    22. //将根节点添加到文档中
    23. doc.AppendChild(books);
    24. //5、给根节点Books创建子节点
    25. XmlElement book1 = doc.CreateElement("Book");
    26. //将book添加到根节点
    27. books.AppendChild(book1);
    28. //6、给Book1添加子节点
    29. XmlElement name1 = doc.CreateElement("Name");
    30. name1.InnerText = "金瓶梅";
    31. book1.AppendChild(name1);
    32. XmlElement price1 = doc.CreateElement("Price");
    33. price1.InnerText = "10";
    34. book1.AppendChild(price1);
    35. XmlElement des1 = doc.CreateElement("Des");
    36. des1.InnerText = "好看";
    37. book1.AppendChild(des1);
    38. XmlElement book2 = doc.CreateElement("Book");
    39. books.AppendChild(book2);
    40. XmlElement name2 = doc.CreateElement("Name");
    41. name2.InnerText = "金瓶梅";
    42. book2.AppendChild(name2);
    43. XmlElement price2= doc.CreateElement("Price");
    44. price2.InnerText = "10";
    45. book2.AppendChild(price2);
    46. XmlElement des2 = doc.CreateElement("Des");
    47. des2.InnerText = "好看";
    48. book2.AppendChild(des2);
    49. doc.Save("Books.xml");
    50. Console.WriteLine("保存成功");
    51. Console.ReadKey();
    52. }
    53. }
    54. }

    最后保存的位置在
    E:\VS2019_workspace\ConsoleApp1\bin\Debug\netcoreapp3.1\Books.xml
    image.png

    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. </Books>