C#中使用XmlDocument類來創(chuàng)建和修改XML格式的數(shù)據(jù)文件
通過XmlDocument類修改XML文檔數(shù)據(jù),通常需要以下幾個主要步驟或其中幾個步驟。
(1)獲取一個包含XML文檔數(shù)據(jù)的XmlDocument類對象,通常有兩種方法來實現(xiàn)這個功能:
通過XmlDocument類的構造函數(shù)創(chuàng)建不包含任何結點的空對象,常用默認構造函數(shù)。
(2)通過XmlDocument類的ChildNodes和Item屬性獲取某個結點(XmlNode類型),通過XmlNode的Name、Value、InnerText等屬性修改選中結點的數(shù)據(jù)。
(3)通過XmlDocument類的CreateElement()和CreateAttribute()方法,創(chuàng)建新的元素結點和屬性結點,并通過XmlNode的Name、Value、InnerText等屬性設置新結點的屬性。CreateElement()和CreateAttribute()的常用定義如下。
CreateElement(string name):創(chuàng)建具有指定限定名的元素結點,其中name表示元素結點的限定名,返回XmlElement類型對象。
CreateAttribute(string name):創(chuàng)建具有指定限定名的屬性結點,其中name表示屬性結點的限定名,返回XmlAttribute類型對象。
(4)通過XmlDocument類的CreateXmlDeclaration()方法創(chuàng)建一個XML文檔說明,并通過XmlDocument.AppendChild()方法添加到XML文檔中。CreateXmlDeclaration()的定義如下。
CreateXmlDeclaration(string version, string encoding, string standalone):創(chuàng)建一 個具有指定版本和編碼的XML文檔說明。其中,version表示版本,encoding表示XML文檔的編碼格式,默認為utf-8,standalone表示是否在XML聲明上寫出獨立屬性,可選yes或no。
(5)通過XmlDocument類的CreateComment()方法創(chuàng)建一個具有指定文本的XML注釋,并通過XmlDocument.AppendChild()方法添加到XML文檔中。
CreateComment(string data):創(chuàng)建包含指定文本的XML注釋,其中data表示注釋的文本內容。返回XmlComment類型對象。
(6)通過XmlDocument類的Save()方法保存一個XML文檔數(shù)據(jù)到文件或數(shù)據(jù)流,它包含以下重載版本:
Save(Stream sr):將內存中的XML文檔數(shù)據(jù)保存到指定的數(shù)據(jù)流,其中,sr表示一個特定的可以寫入的數(shù)據(jù)流。
Save(string filename):將內存中的XML文檔數(shù)據(jù)保存到指定的文件,其中,filename表示XML文件名。
Save(TextWriter tw):將內存中的XML文檔數(shù)據(jù)保存到指定的文本數(shù)據(jù)寫入器,其中,tw表示一個文本寫入器對象。
Save(XmlWriter xw):將內存中的XML文檔數(shù)據(jù)保存到指定的XML數(shù)據(jù)寫入器,其中,xw表示一個XML數(shù)據(jù)寫入器對象。
簡單例子
寫入文檔:
static void Main(string[] args) { XmlDocument doc = new XmlDocument();//實例化文檔對象 if (File.Exists("student.xml"))//如果文件已存在,載入文檔 { doc.Load("student.xml"); } else//否則 { XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8","yes");//設置聲明 doc.AppendChild(dec); XmlElement root = doc.CreateElement("root");//加入根節(jié)點 doc.AppendChild(root); } XmlElement student = doc.CreateElement("student");//插入一個student節(jié)點 student.SetAttribute("id", "120");//設置id屬性 student.SetAttribute("age", "22");//設置age屬性 student.InnerText = "張三";//設置中間文本 doc.DocumentElement.AppendChild(student);//將student節(jié)點連接在根節(jié)點上 doc.Save("student.xml");//保存文檔 }
執(zhí)行3次后產生的xml文檔:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <root> <student id="120" age="22">張三</student> <student id="120" age="22">張三</student> <student id="120" age="22">張三</student> </root>
相關文章
C# 大數(shù)據(jù)導出word的假死報錯的處理方法
C# 大數(shù)據(jù)導出word的假死報錯的處理方法,需要的朋友可以參考一下2013-03-03C#動態(tài)創(chuàng)建button按鈕的方法實例詳解
這篇文章主要介紹了C#動態(tài)創(chuàng)建button按鈕的方法實例詳解的相關資料,需要的朋友可以參考下2017-06-06