DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
用 C# 操作 XML:新增、修改、刪除與走訪節點的完整示例
編輯:XML詳解     

XmlDocument 是把 XML 當成文件物件模型來操作的經典做法,DOM 的樹狀思維很適合處理「找出某個節點、改一改、存回去」這類需求。以下用一份 bookstore.xml 走過增刪改查四個動作。

起始文件:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
</bookstore>

一、新增節點

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("bookstore.xml");

XmlNode root = xmlDoc.SelectSingleNode("bookstore");   // 找到 bookstore 節點
XmlElement xe1 = xmlDoc.CreateElement("book");          // 建立 book 節點
xe1.SetAttribute("genre", "李贊紅");                    // 設定 genre 屬性
xe1.SetAttribute("ISBN", "2-3631-4");                   // 設定 ISBN 屬性

XmlElement xesub1 = xmlDoc.CreateElement("title");
xesub1.InnerText = "C# 從入門到精通";
xe1.AppendChild(xesub1);

XmlElement xesub2 = xmlDoc.CreateElement("author");
xesub2.InnerText = "候捷";
xe1.AppendChild(xesub2);

XmlElement xesub3 = xmlDoc.CreateElement("price");
xesub3.InnerText = "58.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);                                  // 掛到 bookstore 底下
xmlDoc.Save("bookstore.xml");

結果多出一筆紀錄:

<book genre="李贊紅" ISBN="2-3631-4">
  <title>C# 從入門到精通</title>
  <author>候捷</author>
  <price>58.3</price>
</book>

二、修改節點

把 genre 屬性值為「李贊紅」的節點改成「update李贊紅」,並把它的 author 子節點文字改為「亞勝」。

XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;

foreach (XmlNode xn in nodeList)
{
    XmlElement xe = (XmlElement)xn;
    if (xe.GetAttribute("genre") == "李贊紅")
    {
        xe.SetAttribute("genre", "update李贊紅");

        XmlNodeList nls = xe.ChildNodes;
        foreach (XmlNode xn1 in nls)
        {
            XmlElement xe2 = (XmlElement)xn1;
            if (xe2.Name == "author")
            {
                xe2.InnerText = "亞勝";
                break;
            }
        }
        break;
    }
}

xmlDoc.Save("bookstore.xml");

三、刪除屬性與節點

移除 fantasy 那筆的 genre 屬性,並清空「update李贊紅」那筆節點。

XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;

foreach (XmlNode xn in xnl)
{
    XmlElement xe = (XmlElement)xn;
    if (xe.GetAttribute("genre") == "fantasy")
    {
        xe.RemoveAttribute("genre");        // 刪除屬性
    }
    else if (xe.GetAttribute("genre") == "update李贊紅")
    {
        xe.RemoveAll();                     // 刪除該節點的全部內容
    }
}

xmlDoc.Save("bookstore.xml");

結果如下,第一筆少了 genre,第二筆只剩一對空標籤:

<book ISBN="2-3631-4">
  <title>Oberon's Legacy</title>
  <author>Corets, Eva</author>
  <price>5.95</price>
</book>
<book></book>

若要把整個節點從樹上摘掉,應該改用 parent.RemoveChild(xe);RemoveAll() 只清內容,節點本身仍在。

四、走訪並顯示所有資料

XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl = xn.ChildNodes;

foreach (XmlNode xnf in xnl)
{
    XmlElement xe = (XmlElement)xnf;
    Console.WriteLine(xe.GetAttribute("genre"));   // 屬性值
    Console.WriteLine(xe.GetAttribute("ISBN"));

    XmlNodeList xnf1 = xe.ChildNodes;
    foreach (XmlNode xn2 in xnf1)
    {
        Console.WriteLine(xn2.InnerText);          // 子節點文字
    }
}

兩個實務提醒

一是選擇器。SelectSingleNode("bookstore") 這類寫法在文件結構單一時沒問題,但一旦要按屬性篩選,直接改用 XPath(例如 /bookstore/book[@genre='fantasy'])會比手寫 foreach 加 if 清楚得多,也少掉型別轉換的風險。

二是編碼。範例宣告 encoding="gb2312",存檔時 XmlDocument.Save 會依宣告處理,但如果你用 XmlWriter 自行控制輸出,要記得把 XmlWriterSettings.Encoding 設成同一個編碼,否則中文很容易變成亂碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved