程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> C#中使用XML——實現DOM

C#中使用XML——實現DOM

編輯:.NET實例教程

在前兩篇文章中我們討論了XML文件的讀取和寫入,但都是基於流模型的解決方案,今天我們就來談談在C#中如何實現DOM,DOM確實有它的不足,但在編程工作中它還是不可或缺的技術。下面我們來簡單了解一下DOM的相關知識。

DOM的全稱是Document Object Model(文檔對象模型),它是來自W3C的官方標准,它允許按照W3C標准W3C DOM Level1和W3C DOM Level2的規范所定義的規則,通過編程來讀取,操縱和修改XML文檔。DOM的工作方式是:首先將XML文檔一次性的裝入內存,然後根據文檔中定義的元素和屬性在內存中創建一個“樹型結構”也就是一個文檔對象模型,這裡的含義其實是把文檔對象化,文檔中每個節點對應著模型中一個對象,而我們都知道對象提供編程接口,所以在Application中我們正是使用這組對象來訪問XML文檔進而操作XML文檔,下圖闡述了Application和DOM交互的過程:




DOM既然是在內存中創建樹型結構視圖進而提供編程接口,那我們就以下面這個XML片段來說明DOM是如何創建樹型結構的:

<parent>

<child id=”123”>text here</child>

</parent>

如果用DOM加載以上文檔,它將在內存中創建的樹型結構如下圖:




DOM的關鍵在於它允許直接更新內存中的樹型結構,而不必重定向到其他輸出,因此,添加、更新或刪除結構中信息的操作效率更高。而作為程序員的我們重要的是要了解DOM所提供的編程接口以實現對XML文檔進行操作,事實上,.NET Framework定義了一組類用於反映DOM的體系結構,下面來看一下.Net DOM的繼承結構:




在上圖中所有弧角矩形中所包含的類描述了所有可能在XML文檔中出現的節點類型,而操作XML文檔不外乎是操作其中的節點,這些類又都是從XmlNode類派生而來,所以我們今天的主題是討論XmlNode類和它的子類XMLDocument,下面對這些類做簡單的介紹:

XMLNode類:

該類是DOM中所有其他節點的抽象基類,它定義所有在更低級的類中繼承或重寫的成員。它表示XML文檔中的單一節點,它提供了用於導航DOM樹型結構的基本方法和屬性,使用XMLNodeType枚舉器可以枚舉其下的所有節點類型。以下介紹該類的部分屬性和方法:

屬性:

[C#]

public virtual bool HasChildNodes {get;} 獲取一個值,該值指示當前節點是否有任何子節點

public virtual XMLNodeList ChildNodes {get;} 獲取當前節點的所有子節點

public virtual XMLNode FirstChild {get;} 獲取當前節點的第一個子級

public virtual XMLNode LastChild {get;} 獲取當前節點的最後一個子級

public virtual XMLNode ParentNode {get;} 獲取當前節點的父級

public virtual XMLNode NextSibling {get;} 獲取當前節點的下一個兄弟節點

public virtual XMLNode PreviousSibling {get;} 獲取當前節點的上一個兄弟節點

public virtual string InnerText {get; set;} 獲取或設置當前節點及其所有子節點的文本內容的串聯值

public virtual string InnerXML {get; set;} 獲取或設置僅代表當前節點的子節點的標記

public virtual string OuterXML {get;} 獲取表示當前節點及其所有子節點的標記

方法:

public XMLNodeList SelectNodes(string); 選擇文檔中匹配 XPath 表達式的節點列表

public XmlNode SelectSingleNode(string); 選擇文檔中匹配 XPath 表達式的第一個 XMLNode

public virtual XmlNode AppendChild(XMLNode newChild) 將指定的節點添加到該節點的子節點列表的末尾

public virtual XmlNode PrependChild(XMLNode newChild) 將指定的節點添加到該節點的子節點列表的開頭

public virtual XmlNode RemoveChild(XMLNode oldChild) 移除指定的子節點

public virtual XmlNode ReplaceChild(XmlNode newChild,XMLNode oldChild) 用 newChild 節點替換子節點 oldChild

XMLNodeList類:

該類表示XMLNode的有序集合,它有以下常用成員:

Count——以整數形式返回XMLNodeList中的節點數

ItemOf——搜索在指定索引處的節點

GetEnumerator()——提供迭代遍歷節點列表的foreach樣式

Item()——返回參數指定的索引處的節點

XMLDocument類:

XmlDocument類是XML文檔的.Net表示形式,它代表了內存中樹型結構的文檔節點(所有的節點都在文檔節點下),XmlDocument類包含所有的CreateXXX()方法,這些方法允許創建所有派生自XmlNode的類型的節點,通常將該類與XmlNode類一起使用以完成對文檔的操作,該類有一個Load()方法用於加載XML文檔,該方法的一個重載版本允許從XmlTextReader加載文檔,這給我們帶來的好處是在操作較大的文檔時我們可以先使用XMLTextReader過濾不相關的文檔部分,這樣即解決了DOM所帶來的資源損耗問題又可以保留DOM對文檔操控的便利性,該類的Save()方法用於保存文檔。



接下來用一個簡單的例子來說明在C#中如何實現DOM,照舊看代碼前先看下運行效果圖:




LoadXML按紐用於加載XML文檔,LoadXMLReader按紐使用XmlTextReader加載文檔,SaveXML按紐保存文檔,SaveXMLWriter按紐將文檔保存到XMLTextWriter中,Add Product按紐添加節點,Replace Product按紐替換節點,Change Order按紐修改文檔,Remove Product Info按紐移除節點。



DomOperation類封裝了所有按紐功能的實現,

代碼如下:

namespace DOMSamples

{

using System;

using System.XML;

using System.Text;

using System.Windows.Forms;

using System.ComponentModel;



/// <summary>

/// DomOperation 提供對XML文件操作的類

/// </summary>

/// <remarks>

/// 該類用於提供對XML文件進行一般的操作,如(添加,刪除,替換節點,加載,保存文件)等,該類內部實現采用DOM技術。

/// </remarks>

public class DomOperation : IDisposable

{

private string _XMLPath;

private XmlDocument XMLDoc;



#region DomOperation 構造器



/// <summary>

/// 默認構造器,對該類成員進行默認賦值

/// </summary>

public DomOperation()

{ this._XMLPath = string.Empty;

this.XMLDoc = null;

}



/// <summary>

/// 帶參構造器,對該類成員進行初始賦值

/// </summary>

/// <param name="xmlPath">XML文件路徑</param>

public DomOperation(string XMLPath)

{

this._xmlPath = XMLPath;

this.XMLDoc = null;

}



#endregion



#region DomOperation 資源釋放方法



/// <summary>

/// 清理該對象所有正在使用的資源

/// </summary>

public void Dispose()

{

this.Dispose(true);

GC.SuppressFinalize(this);

}



/// <summary>

/// 釋放該對象的實例變量

/// </summary>

/// <param name="disposing"></param>

protected virtual void Dispose(bool disposing)

> {

if (!disposing)

return;



if (this._XMLPath != null)

{

this._XMLPath = null;

}



if (this.XMLDoc != null)

{

this.XMLDoc = null;

}

}



#endregion



#region DomOperation 屬性



/// <summary>

/// 獲取或設置XML文件的路徑

/// </summary>

public string XMLPath

{

get

{

return _XMLPath;

}

set

{

this._XMLPath = value;

}

}



#endregion



/// <summary>

/// 加載XML文件

/// </summary>

/// <remarks>

/// 該方法使用XML文件的路徑加載XML文件並返回整個XML文件的內容

/// </remarks>

/// <returns>整個XML文件的內容</returns>

public string Load()

{

xmlDoc = new XMLDocument();



try

{

xmlDoc.Load(this._XMLPath);

}

catch(XmlException XMLExp)

{

throw new XmlException(XMLExp.ToString());

}



return xmlDoc.OuterXML;

}



/// <summary>

/// 加載XML文件

/// </summary>

/// <remarks>

/// 該方法使用XmlReader在XML文檔中定位並加載XML文件最後返回XML文件的內容

/// </remarks>

/// <param name="nodeType">將要定位的節點類型</param>

/// <param name="localName">將要定位的節點名稱</param>

/// <returns>XML文件的內容</returns>

public string LoadByXmlReader(XMLNodeType nodeType, string localName)

{

string XMLStr = string.Empty;

XmlTextReader xmlTxtRd = new XmlTextReader(this._XMLPath);

xmlDoc = new XMLDocument();



try

{

// 在文檔中定位

while(XMLTxtRd.Read())

{

if (XMLTxtRd.NodeType == nodeType)

if(XMLTxtRd.LocalName == localName)

break;

}

xmlDoc.Load(XMLTxtRd);

XMLTxtRd.Close();



xmlStr += "===== OuterXML =====";

XMLStr += System.Environment.NewLine;

xmlStr += xmlDoc.FirstChild.OuterXML;

XMLStr += System.Environment.NewLine;

XMLStr += System.Environment.NewLine;



xmlStr += "===== InnerXML =====";

XMLStr += System.Environment.NewLine;

xmlStr += xmlDoc.FirstChild.InnerXML;

XMLStr += System.Environment.NewLine;

XMLStr += System.Environment;



XMLStr += "===== InnerText =====";

XMLStr += System.Environment.NewLine;

xmlStr += XMLDoc.FirstChild.InnerText;

XMLStr += System.Environment.NewLine;

XMLStr += System.Environment.NewLine;



XMLStr += "===== Value =====";

XMLStr += System.Environment.NewLine;

xmlStr += XMLDoc.FirstChild.ChildNodes[0].ChildNodes[0].Value + " " +

XMLDoc.FirstChild.ChildNodes[1].ChildNodes[0].Value + " " +

XMLDoc.FirstChild.ChildNodes[2].ChildNodes[0].Value;

XMLStr += System.Environment.NewLine;

XMLStr += System.Environment.NewLine;

}

catch(XmlException XMLExp)

{

throw new XmlException(XMLExp.ToString());

}

finally

{

if (xmlTxtRd != null && XMLTxtRd.ReadState != ReadState.Closed)

XMLTxtRd.Close();

}



return XMLStr;

}



/// <summary>

/// 保存XML文件

/// </summary>

/// <remarks>

/// 該方法將傳入的XML文本保存在傳入的路徑中最後返回XML文件的內容

/// </remarks>

/// <param name="xmlText">XML文本</param>

/// <param name="savePath">保存路徑</param>

/// <returns>XML文件的內容</returns>

public string Save(string XMLText, string savePath)

{

xmlDoc = new XMLDocument();



try

{

xmlDoc.LoadXml(XMLText);

XMLDoc.Save(savePath);



XMLDoc.Load(savePath);

}

catch(XmlException XMLExp)

{

throw new XmlException(XMLExp.ToString());

}



return xmlDoc.OuterXML;

}



/// <summary>

/// 保存XML文件

/// </summary>

/// <remarks>

/// 該方法將傳入的XML文本保存在XmlTextWriter編寫器中並使用傳入的路徑構造該編寫器最後返回XML文件的內容

/// </remarks>

/// <param name="xmlText">XML文本</param>

/// <param name="savePath">保存路徑</param>

/// <returns>XML文件的內容</returns>

public string SaveByXmlWriter(string XMLText, string savePath)

{

XmlTextWriter xmlTxtWt = new XMLTextWriter(savePath,Encoding.Unicode);

xmlDoc = new XMLDocument();



try

{

xmlDoc.LoadXml(XMLText);

xmlDoc.Save(XMLTxtWt);

XMLTxtWt.Close();



XMLDoc.Load(savePath);

}

catch(XmlException XMLExp)

{

throw new XmlException(XMLExp.ToString());

}

finally

{

if (xmlTxtWt != null && XMLTxtWt.WriteState != WriteState.Closed)

XMLTxtWt.Close();

}



return xmlDoc.OuterXML;

}



/// <summary>

/// 添加子節點

/// </summary>

/// <remarks>

/// 該方法利用傳入的父節點路徑選擇該節點並將傳入的XML文檔片段添加到該父節點下最後返回添加後XML文件的內容

/// </remarks>

/// <param name="XMLDoc"></param>

/// <param name="xmlDocFrag">XML文檔片段</param>

/// <param name="parentNodePath">父節點路徑</param>

/// <returns>添加後XML文件的內容</returns>

public string AddChildNode(XmlDocument xmlDoc, XmlDocumentFragment XMLDocFrag, string parentNodePath)

{

this.xmlDoc = XMLDoc;



XmlElement selectEle = (XmlElement)XMLDoc.SelectSingleNode(parentNodePath);

selectEle.AppendChild(XMLDocFrag.FirstChild);



return this.xmlDoc.OuterXML;

}



/// <summary>

/// 替換子節點

/// </summary>

/// <remarks>

/// 該方法利用父節點路徑選擇該節點並用傳入的XML文檔片段替換該父節點下的第i個子節點最後返回替換後的XML文件的內容

/// </remarks>

/// <param name="XMLDoc"></param>

/// <param name="xmlDocFrag">XML文檔片段</param>

/// <param name="parentNodePath">父節點路徑</param>

/// <param name="i">第i個子節點</param>

/// <returns>替換後的XML文件的內容</returns>

public string ReplaceChildNode(XmlDocument xmlDoc, XmlDocumentFragment XMLDocFrag, string parentNodePath, int i)

{

this.xmlDoc = XMLDoc;



XmlElement selectEle = (XmlElement)XMLDoc.SelectSingleNode(parentNodePath);

XmlElement childEle = (XMLElement)selectEle.ChildNodes[i];

selectEle.ReplaceChild(XMLDocFrag.FirstChild,childEle);



return this.xmlDoc.OuterXML;

}



/// <summary>

/// 移除子節點

/// </summary>

/// <remarks>

/// 該方法利用傳入的父節點名稱選擇該父節點並利用傳入的子節點名稱選擇該子節點選定後使用父節點的RemoveChild方法移除子節點

/// 最後返回移除後XML的文件內容

/// </remarks>

/// <param name="parentNodeName">父節點名稱</param>

/// <param name="childNodeName">子節點名稱</param>

/// <returns>移除後XML的文件內容</returns>

public string RemoveChildNode(string parentNodeName, string childNodeName)

{

xmlDoc = new XMLDocument();



xmlDoc.Load(this._XMLPath);

XmlNodeList parentNodeList = XMLDoc.GetElementsByTagName(parentNodeName);



foreach (XMLNode parentNode in parentNodeList)

{

XMLNodeList childNodeList = parentNode.SelectNodes(childNodeName);



foreach (XMLNode childNode in childNodeList)

{

parentNode.RemoveChild(childNode);

}

}



return xmlDoc.OuterXML;

}

}

}

窗口程序代碼如下:

namespace DOMSamples

{

using System;

using System.XML;

using System.Text;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;



/// <summary>

/// Form1 的摘要說明。

/// </summary>

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.TextBox textBox1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.Button button3;

private System.Windows.Forms.Button button4;

private System.Windows.Forms.Button button5;

private System.Windows.Forms.Button button6;

private System.Windows.Forms.Button button7;

private System.Windows.Forms.Button button8;

private string XMLPath;

/// <summary>

/// 必需的設計器變量。

/// </summary>

private System.ComponentModel.Container components = null;



public Form1()

{

//

// Windows 窗體設計器支持所必需的

//

InitializeComponent();



//

// TODO: 在 InitializeComponent 調用後添加任何構造函數代碼

//

}



/// <summary>

/// 清理所有正在使用的資源。

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}



#region Windows 窗體設計器生成的代碼
/// <summary>

/// 設計器支持所需的方法 - 不要使用代碼編輯器修改

/// 此方法的內容。

/// </summary>

private void InitializeComponent()

{

this.textBox1 = new System.Windows.Forms.TextBox();

this.button1 = new System.Windows.Forms.Button();

this.button2 = new System.Windows.Forms.Button();

this.button3 = new System.Windows.Forms.Button();

this.button4 = new System.Windows.Forms.Button();

this.button5 = new System.Windows.Forms.Button();

this.button6 = new System.Windows.Forms.Button();

this.button7 = new System.Windows.Forms.Button();

this.button8 = new System.Windows.Forms.Button();

this.Susp ndLayout();

//

// textBox1

//

this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

| System.Windows.Forms.AnchorStyles.Left)

| System.Windows.Forms.AnchorStyles.Right)));

this.textBox1.Location = new System.Drawing.Point(8, 8);

this.textBox1.Multiline = true;

this.textBox1.Name = "textBox1";

this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;

this.textBox1.Size = new System.Drawing.Size(776, 296);

this.textBox1.TabIndex = 0;

this.textBox1.Text = "";

//

// button1

//

this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button1.Location = new System.Drawing.Point(8, 312);

this.button1.Name = "button1";

this.button1.Size = new System.Drawing.Size(56, 23);

this.button1.TabIndex = 1;

this.button1.Text = "LoadXML";

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// button2

//

this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button2.Location = new System.Drawing.Point(72, 312);

this.button2.Name = "button2";

this.button2.Size = new System.Drawing.Size(96, 23);

this.button2.TabIndex = 2;

this.button2.Text = "LoadXMLReader";

this.button2.Click += new System.EventHandler(this.button2_Click);

//

// button3

//

this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button3.Location = new System.Drawing.Point(176, 312);

this.button3.Name = "button3";

this.button3.Size = new System.Drawing.Size(56, 23);

this.button3.TabIndex = 3;

this.button3.Text = "SaveXML";

this.button3.Click += new System.EventHandler(this.button3_Click);

//

// button4

//

this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button4.Location = new System.Drawing.Point(240, 312);

this.button4.Name = "button4";

this.button4.Size = new System.Drawing.Size(96, 23);

this.button4.TabIndex = 4;

this.button4.Text = "SaveXMLWriter";

this.button4.Click += new System.EventHandler(this.button4_Click);

//

// button5

//

this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button5.Location = new System.Drawing.Point(344, 312);

this.button5.Name = "button5";

this.button5.Size = new System.Drawing.Size(80, 23);

this.button5.TabIndex = 5;

this.button5.Text = "Add Product";

this.button5.Click += new System.EventHandler(this.button5_Click);

//

// button6

//

this.button6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button6.Location = new System.Drawing.Point(432, 312);

this.button6.Name = "button6";

this.button6.Size = new System.Drawing.Size(112, 23);

this.button6.TabIndex = 6;

this.button6.Text = "Replace Product";

this.button6.Click += new System.EventHandler(this.button6_Click);

//

// button7

//

this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button7.Location = new System.Drawing.Point(552, 312);

this.button7.Name = "button7";

this.button7.Size = new System.Drawing.Size(88, 23);

this.button7.TabIndex = 7;

this.button7.Text = "Change Order";

this.button7.Click += new System.EventHandler(this.button7_Click);

//

// button8

//

this.button8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button8.Location = new System.Drawing.Point(648, 312);

this.button8.Name = "button8";

this.button8.Size = new System.Drawing.Size(136, 23);

this.button8.TabIndex = 8;

this.button8.Text = "Remove Product Info";

this.button8.Click += new System.EventHandler(this.button8_Click);

//

// Form1

// 

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

this.ClIEntSize = new System.Drawing.Size(792, 341);

this.Controls.Add(this.button8);

this.Controls.Add(this.button7);

this.Controls.Add(this.button6);

this.Controls.Add(this.button5);

this.Controls.Add(this.button4);

this.Controls.Add(this.button3);

this.Controls.Add(this.button2);

this.Controls.Add(this.button1);

this.Controls.Add(this.textBox1);

this.Name = "Form1";

this.Text = "DOMSample Application";

this.ResumeLayout(false);

//

// XMLPath

//

this.xmlPath = "../../sample.XML";



}

#endregion



/// <summary>

/// 應用程序的主入口點。

/// </summary>

[STAThread]

static void Main()

{

Application.Run(new Form1());

}



private void button1_Click(object sender, System.EventArgs e)

{

this.textBox1.Text = "";

DomOperation DomOper = new DomOperation(this.XMLPath);



try

{

this.textBox1.Text = DomOper.Load();

}

catch(XmlException XMLExp)

{

MessageBox.Show(XMLExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



private void button2_Click(object sender, System.EventArgs e)

{

this.textBox1.Text = "";

DomOperation DomOper = new DomOperation(this.XMLPath);



try

{

this.textBox1.Text = DomOper.LoadByXmlReader(XMLNodeType.Element,"Product");

}

catch(XmlException XMLExp)

{

MessageBox.Show(XMLExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



private void button3_Click(object sender, System.EventArgs e)

{

string savePath = "../../rootDoc.XML";

string XMLText = "<root><para>some para text</para></root>";

DomOperation DomOper = new DomOperation();



try

{

this.textBox1.Text = DomOper.Save(XMLText,savePath);

}

catch(XmlException XMLExp)

{

MessageBox.Show(XMLExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



private void button4_Click(object sender, System.EventArgs e)

{

string savePath = "../../rootDoc2.XML"; 


string xmlText = "<?XML version='1.0' encoding='utf-8' ?><root><para>some para text</para></root>";

DomOperation DomOper = new DomOperation();



try

{

this.textBox1.Text = DomOper.SaveByXmlWriter(XMLText,savePath);

}

catch(XmlException XMLExp)

{

MessageBox.Show(XMLExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



private void button5_Click(object sender, System.EventArgs e)

{

DomOperation DomOper = new DomOperation();

XmlDocument xmlDoc = new XMLDocument();



try

{

xmlDoc.Load(this.XMLPath);



// 創建一個XML文檔片段

XmlDocumentFragment xmlDocFrag = XMLDoc.CreateDocumentFragment();



// 創建父根元素節點test:Product

XmlElement proEle = XMLDoc.CreateElement("test","Product","uri:test");



// 創建屬性並添加到根元素test:Product中

XmlAttribute proIdAtt = XMLDoc.CreateAttribute("ProductID");

proIdAtt.Value = "MU78";

proEle.Attributes.SetNamedItem(proIdAtt);



// 創建根元素節點的葉節點

XmlElement colorEle = XMLDoc.CreateElement("color");

colorEle.InnerText = "red";

proEle.AppendChild(colorEle);



XmlElement sizeEle = XMLDoc.CreateElement("size");

sizeEle.InnerText = "M";

proEle.AppendChild(sizeEle);



XmlElement priceEle = XMLDoc.CreateElement("price");

priceEle.InnerText = "125.99";

proEle.AppendChild(priceEle);



// 將根元素添加進XML文檔片段中

XMLDocFrag.AppendChild(proEle);



this.textBox1.Text = DomOper.AddChildNode(xmlDoc,XMLDocFrag,"//ProductFamily");

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



private void button6_Click(object sender, System.EventArgs e)

{

XmlDocument xmlDoc = new XMLDocument();

DomOperation DomOper = new DomOperation();



try

{

xmlDoc.Load("../../sample.XML");



XmlDocumentFragment xmlDocFrag = XMLDoc.CreateDocumentFragment();

> XmlElement proEle = XMLDoc.CreateElement("test","Product","uri:test");



XmlAttribute proIdAtt = XMLDoc.CreateAttribute("ProductID");

proIdAtt.Value = "MU78";

proEle.Attributes.SetNamedItem(proIdAtt);



XmlElement colorEle = XMLDoc.CreateElement("color");

colorEle.InnerText = "red";

proEle.AppendChild(colorEle);



XmlElement sizeEle = XMLDoc.CreateElement("size");

sizeEle.InnerText = "M";

proEle.AppendChild(sizeEle);



XmlElement priceEle = XMLDoc.CreateElement("price");

priceEle.InnerText = "125.99";

proEle.AppendChild(priceEle);



XMLDocFrag.AppendChild(proEle);



this.textBox1.Text = DomOper.ReplaceChildNode(xmlDoc,XMLDocFrag,"//ProductFamily",0);

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}



// 使用InnerXml和InnerText直接修改XML文檔

private void button7_Click(object sender, System.EventArgs e)

{

XmlDocument xmlDoc = new XMLDocument();

xmlDoc.Load("../../sample.XML");



XmlNodeList nodeList = XMLDoc.SelectNodes("//price");



foreach (XMLNode node in nodeList)

{

node.InnerXML = "<currency type='dollar'>" + node.InnerText + "</currency>";

}



this.textBox1.Text = xmlDoc.OuterXML;

}



private void button8_Click(object sender, System.EventArgs e)

{

DomOperation DomOper = new DomOperation(this.XMLPath);



try

{

this.textBox1.Text = DomOper.RemoveChildNode("Company","ProductFamily");

}

catch(Exception exp)

{

MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}

}

}

程序中使用到的XML文件如下:

sample.XML

<?XML version="1.0" encoding="utf-8" ?>

<Catalog XMLns:test="uri:test">

<Company email="[email protected]" name="Celtic Productions">

<ProductFamily familyID="pftops" LastUpdate="2001-08-26T 18:39:09" buyersURI="http://www.deltabis.com/buyers/tops">

<test:Product ProductID="CFC4">

<color>black</color>

<size>L</size>

<price>32.99</price>

</test:Product>

</ProductFamily>

</Company>

</Catalog>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved