DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
實例講解 XML 文件的基本操作:新增、修改、刪除與查詢
編輯:XML詳解     

本文以一份名為 bookstore.xml 的文件為例,用 C# 的 XML DOM 逐步示範增刪改查四種基本操作。

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

一、新增節點

往 <bookstore> 中插入一個新的 <book> 節點:

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 = "CS 從入門到精通";             // 設定文字節點
xe1.AppendChild(xesub1);                         // 掛到 <book> 底下

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");

執行後的結果:

<?XML version="1.0" encoding="gb2312"?>
<bookstore>
   <book genre="fantasy" ISBN="2-3631-4">
     <title>Oberons Legacy</title>
     <author>Corets, Eva</author>
     <price>5.95</price>
   </book>
   <book genre="李贊紅" ISBN="2-3631-4">
     <title>CS 從入門到精通</title>
     <author>候捷</author>
     <price>58.3</price>
   </book>
</bookstore>

二、修改節點

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

XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach(XmlNode xn in nodeList)                   // 遍歷所有子節點
{
    XmlElement xe = (XmlElement)xn;               // 轉型為 XmlElement
    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");

結果中該節點已變為 <book genre="update李贊紅" ISBN="2-3631-4">,其 <author> 文字成為「亞勝」。

三、刪除屬性與節點

刪除第一個 book 節點的 genre 屬性,並移除第二個 book 節點的全部內容:

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

foreach(XmlNode xn in xnl)
{
    XmlElement xe = (XmlElement)xn;

    if(xe.GetAttribute("genre") == "fantasy")
    {
        xe.RemoveAttribute("genre");       // 刪除 genre 屬性
    }
    else if(xe.GetAttribute("genre") == "update李贊紅")
    {
        xe.RemoveAll();                    // 刪除該節點所有內容
    }
}
xmlDoc.Save("bookstore.xml");

注意 RemoveAll() 只清掉子節點與屬性,元素本身仍留在文件中,因此結果會出現一個空的 <book></book>。若要把節點整個從父節點摘掉,應該改用 xe.ParentNode.RemoveChild(xe)。

四、讀取並顯示資料

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);      // 顯示子節點文字
    }
}

五、實務上的兩個封裝範例

把上述技巧組合起來,就能封裝成可重複使用的工具方法。以下是一個把業務物件轉成 XML 字串的寫法:

public static string DataToXml(string _ip, string _xmlType, bool _issaveXML,
                         string _contenttype, string _message,
                         string _sendtime, string _toip)
{
    DataParser dp = new DataParser();
    dp.Message = _message;
    dp.IP = _ip;
    dp.XmlType = _xmlType;
    dp.isSaveXml = _issaveXML;
    dp.ContentType = _contenttype;
    dp.Sendtime = _sendtime;
    dp.Toip = _toip;

    XmlDocument doc = new XmlDocument();
    XmlDeclaration newDec = doc.CreateXmlDeclaration("1.0", null, null);
    doc.AppendChild(newDec);

    XmlElement newRoot = doc.CreateElement("Requests");
    doc.AppendChild(newRoot);

    XmlElement newtitle = doc.CreateElement("Request");
    newtitle.SetAttribute("time", dp.Sendtime);
    newRoot.AppendChild(newtitle);

    XmlElement from = doc.CreateElement("from");
    from.SetAttribute("ip", dp.IP);
    from.SetAttribute("type", dp.XmlType);
    from.SetAttribute("ctntype", dp.ContentType);

    // 用 CDATA 承載訊息本文,避免內容含特殊字元時破壞結構
    XmlNode xnfrom = doc.CreateNode(XmlNodeType.CDATA, "content", null);
    xnfrom.InnerText = _message;
    from.PrependChild(xnfrom);
    newtitle.AppendChild(from);

    XmlElement to = doc.CreateElement("to");
    to.SetAttribute("ip", dp.Toip);
    newtitle.AppendChild(to);

    return doc.OuterXml;
}

反過來解析成物件的方法:

/// <summary>
/// 資料解包:將 XML 解析成 DataParser 物件陣列
/// </summary>
public static DataParser[] XmlToData(string outXML)
{
    DataParser[] dp = null;
    try
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(outXML);

        XmlNode rootnode = doc.SelectSingleNode("Requests");
        XmlNodeList bodynodelist = rootnode.SelectNodes("Request");
        dp = new DataParser[bodynodelist.Count];

        int i = 0;
        foreach(XmlNode sn in bodynodelist)
        {
            XmlElement xe = (XmlElement)sn;
            XmlNode xn = sn.SelectSingleNode("from");
            dp[i] = new DataParser();
            dp[i].IP = (xn as XmlElement).Attributes["ip"].Value;
            dp[i].Message = xn.InnerText;
            dp[i].ContentType = (xn as XmlElement).Attributes["ctntype"].Value;
            dp[i].XmlType = (xn as XmlElement).Attributes["type"].Value;
            dp[i].Sendtime = (sn as XmlElement).Attributes["time"].Value;

            XmlNode xn2 = sn.SelectSingleNode("to");
            dp[i].Toip = (xn2 as XmlElement).Attributes["ip"].Value;
            i++;
        }
    }
    catch(Exception err)
    {
        ChatCommon.Common.ExceptionHand.HandleErr(err.ToString());
    }
    return dp;
}

這裡有個值得學的小技巧:用 CreateNode(XmlNodeType.CDATA, ...) 建立 CDATA 節點來承載訊息本文,這樣即使內容含有 <、& 等字元也不會破壞文件結構。

六、從零建立整份文件

如果手上沒有既有文件,也可以完全用程式碼從頭組裝:

using System;
using System.Xml;

namespace XMLDOM
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration xd = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(xd);

            XmlElement xe = doc.CreateElement("bookstore");
            doc.AppendChild(xe);

            XmlElement xr = doc.CreateElement("book");
            xr.SetAttribute("publish", "thinkbank+1");
            xr.InnerText = "c# 入門";
            xe.AppendChild(xr);

            XmlElement xr2 = doc.CreateElement("book");
            xr2.SetAttribute("publish", "thinkbank+1");
            xr2.InnerText = "j# 入門";
            xe.AppendChild(xr2);

            string xml = doc.OuterXml;

            // 重新載入後用 XPath 取值
            XmlDocument doc2 = new XmlDocument();
            doc2.LoadXml(xml);

            XmlNodeList xnlist = doc2.SelectNodes("//book");
            foreach(XmlNode mynode in xnlist)
            {
                Console.WriteLine(mynode.InnerText);
            }
        }
    }
}

XPath 速查

XML DOM 讓你能以程式方式讀取、處理與修改 XML 文件,而 XPath 表達式則是定位節點的工具。它使用類似 URL 的路徑表示法尋址文件的各個部分,運算結果可能是節點集合、布林值、數字或字串。

與 URL 的異同

URL 由檔案系統中的資料夾與檔案構成層級結構,每一層的名稱唯一,且總是指向單一檔案,路徑相對於特定資料夾計算。XPath 則由 XML 文件中的元素構成層級結構,每一層的元素名稱可以並不唯一,表達式標識的是「所有相符的元素集合」,且相對於特定元素(稱為表達式的「上下文」)計算。這個差異是理解 XPath 的起點。

基本路徑寫法

  • ./author:以句點加斜線起始,明確使用當前上下文,選出所有 <author> 子元素。等效於直接寫 author。
  • /bookstore:以斜線起始,從文件樹的根節點算起。
  • /*:選出根元素本身。
  • //author:雙斜線代表任意深度的遞迴搜尋,選出文件中任何位置的 <author>。
  • .//:從層級結構中的當前上下文所在層級開始往下遞迴。
  • images/background.jpg:從當前上下文節點開始,指向特定路徑上的元素。

運算子

  • /:子運算子,選左側集合的直接子級。
  • //:遞迴下降,在任意深度搜尋指定元素。
  • . 當前上下文;.. 當前節點的父級。
  • * 元素通配符;@ 屬性名稱前綴;@* 屬性通配符。
  • : 命名空間分隔符;( ) 分組;[ ] 挑選器與索引。
  • 算術:+ 加、- 減、div 浮點除法、* 乘、mod 取餘數。

優先順序

分組 ( ) > 挑選器 [ ] > 路徑運算 / 與 //。這造成一個常見誤解:

//comment()[3]   // 選出各父節點下索引為 3 的所有 comment,可能有多個
(//comment())[3]   // 選出整個集合中的第三個 comment,只有一個

另外,分組運算子僅適用於頂層路徑表達式:(//author/degree //author/name) 有效,//author/(degree name) 無效。

常用範例

  • author/first-name:當前上下文中所有 <author> 底下的 <first-name>。
  • bookstore//title:<bookstore> 底下任意深度的所有 <title>,與 bookstore/*/title(只取孫級)不同。
  • book/*/last-name:所有作為 <book> 孫級的 <last-name>。
  • */*:當前上下文的所有孫級元素。
  • @style:當前元素的 style 屬性;price/@Exchange:<price> 的 Exchange 屬性。

屬性不能包含子元素,因此對屬性再往下接路徑運算子會造成語法錯誤;屬性也不能用索引,因為規範並未為屬性定義順序。

比較與集合運算

可用運算子包含 and、or、not()、=、!=、<、<=、>、>=,以及 |(集合聯集)。

author[last-name = "Bob"]         // 至少有一個 last-name 值為 Bob 的所有 author
author[last-name[1] = "Bob"]    // 第一個 last-name 子元素值為 Bob 的所有 author
author/degree[@from != "Harvard"]   // degree 的 from 屬性不等於 Harvard 的所有 author
author[. = "Matthew Bob"]       // 字串值為 Matthew Bob 的所有 author
first-name last-name             // 兩者的聯集
(book magazine)/price            // book 或 magazine 底下所有 price

挑選器(謂詞)

把挑選子句 [pattern] 加到集合上,就能對結果施加約束與分支,作用類似 SQL 的 WHERE:

book[excerpt]            // 至少含一個 excerpt 的所有 book
book[excerpt]/title     // 上述 book 底下所有 title
book[excerpt][title]     // 同時含 excerpt 與 title 的所有 book
book[author/degree]     // 含 author 且該 author 至少有一個 degree 子元素的所有 book

把這四類操作(新增、修改、刪除、查詢)與 XPath 結合起來,你就具備了在 .NET 中處理 XML 文件所需的基本工具箱。實務上唯一要額外小心的是節點集合的修改——在 foreach 遍歷 XmlNodeList 的同時刪除節點容易引發非同步修改的例外,需要刪除時建議先收集目標節點,迴圈結束後再統一處理。

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