Home [C# 筆記][XML] 向 XML 中追加內容
Post
Cancel

[C# 筆記][XML] 向 XML 中追加內容

追加XML文檔有兩種情況:1.文件存在、2.文件不存在

  1. 文件存在:只需要拿到文件的根節點,向下添加子節點
  2. 文件不存在:創建文件第一行,再添加根節點,再加子節點

所以要先判斷 if (File.Exists("Books.xml")){ ... }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
static void Main(string[] args)
{
    //追加XML文檔
    //1.命名空間
    //2.創建xml物件
    XmlDocument doc = new XmlDocument();
    XmlElement books;
    if (File.Exists("Books.xml"))
    {
        //1.文件存在 加載xml
        doc.Load("Books.xml"); //加載xml,才能拿得到
                                //取得文件的根節點
        books = doc.DocumentElement;
    } else
    {
        //2.文件不存在
        //創建第一行
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        doc.AppendChild(dec);

        //創建根節點
        books = doc.CreateElement("Books");
        doc.AppendChild(books);
    }
    
    //5給根節點Books創建子節點
    XmlElement book1 = doc.CreateElement("Book");
    //將book加到根節點
    books.AppendChild(book1);

    //6.給book添加子節點
    //book1
    XmlElement name1 = doc.CreateElement("Name");
    name1.InnerText = "C#開發大全";
    book1.AppendChild(name1);

    XmlElement price1 = doc.CreateElement("Price");
    price1.InnerText = "500";
    book1.AppendChild(price1);

    XmlElement des1 = doc.CreateElement("Des");
    des1.InnerText = "好得不得了";
    book1.AppendChild(des1);

    //book2
    XmlElement book2 = doc.CreateElement("Book");
    books.AppendChild(book2);

    XmlElement name2 = doc.CreateElement("Name");
    name2.InnerText = "Java";
    book2.AppendChild(name2);

    XmlElement price2 = doc.CreateElement("Price");
    price2.InnerText = "300";
    book2.AppendChild(price2);

    XmlElement des2 = doc.CreateElement("Des");
    des2.InnerText = "一看就通";
    book2.AppendChild(des2);

    doc.Save("Books.xml");
    Console.WriteLine("儲存成功");
    Console.ReadKey();
}

https://www.bilibili.com/video/BV1vG411A7my?p=61

This post is licensed under CC BY 4.0 by the author.