C#下使用XmlDocument操作XML詳解
一、XML DOM概述
XML 文檔大小寫敏感、屬性用引號括起來,每一個標(biāo)記都要閉合。
DOM是XML文檔的內(nèi)存中樹狀的表示形式。
繼承關(guān)系圖:
XmlNode;//XML節(jié)點(diǎn) ......XmlDocument;//XML文檔 ............XmlDataDocument;//與Dataset相關(guān)的文檔 ......XmlDocumentFragment;//文檔片段 ......XmlLinkedNode;//連接節(jié)點(diǎn)(抽象類) ............XmlDeclaration;//XML聲明: ............XmlDocumentType;//文檔類型 ............XmlElement;//元素 ............XmlEntityReference;//實體引用節(jié)點(diǎn) ............XmlProcessingInstruction;//處理指令 ............XmlCharacterData;//字符數(shù)據(jù)(抽象類) ..................XmlCDataSection;//CDATA節(jié) ..................XmlComment;//注釋 ..................XmlSignificantWhitespace;//有效空白 ..................XmlWhitespace;//空白 ..................XmlText;//元素或?qū)傩缘奈谋緝?nèi)容 ......XmlAttribute;//屬性 ......XmlEntity;//實體聲明 ......XmlNotation;//表示法聲明
二、XML成員
1、XMl節(jié)點(diǎn):XmlNode
1、屬性:
- Child?Nodes : 所有子節(jié)點(diǎn)。
- First?Child : 第一個子級。
- Has?Child?Nodes :獲是否有任何子節(jié)點(diǎn)。
- Last?Child :最后一個子節(jié)點(diǎn)。
- Parent?Node : 父節(jié)點(diǎn)(針對可以擁有父級的節(jié)點(diǎn))。
- Next?Sibling : 緊接在該節(jié)點(diǎn)之后的兄弟節(jié)點(diǎn)。
- Previous?Sibling : 緊接在該節(jié)點(diǎn)之前的兄弟節(jié)點(diǎn)。
- Inner?Text : 節(jié)點(diǎn)及其所有子節(jié)點(diǎn)的文本值。
- Inner?Xml :子節(jié)點(diǎn)的XML標(biāo)記。
- Outer?Xml : 此節(jié)點(diǎn)及其所有子節(jié)點(diǎn)XML標(biāo)記。
- Node?Type : 獲取當(dāng)前節(jié)點(diǎn)的類型。
- Value :節(jié)點(diǎn)的值。
- Attributes : 節(jié)點(diǎn)的特性XmlAttributeCollection。
- Owner?Document : 節(jié)點(diǎn)所屬的 XmlDocument。
2、方法:
- Append?Child(Xml?Node) : 添加到該節(jié)點(diǎn)的子節(jié)點(diǎn)列表的末尾。
- Prepend?Child(Xml?Node) : 追加到該節(jié)點(diǎn)的子節(jié)點(diǎn)列表的開頭。
- Insert?After(Xml?Node, Xml?Node) : 將指定的節(jié)點(diǎn)緊接著插入指定的節(jié)點(diǎn)之后。
- Insert?Before(Xml?Node, Xml?Node) : 將指定的節(jié)點(diǎn)緊接著插入指定的節(jié)點(diǎn)之前。
- Remove?All() : 移除當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn)和/或?qū)傩浴?/li>
- Remove?Child(Xml?Node) : 移除指定的子節(jié)點(diǎn)。
- Replace?Child(Xml?Node, Xml?Node) : 用 oldChild 節(jié)點(diǎn)替換子節(jié)點(diǎn) newChild。
- Select?Nodes(String) : 選擇匹配 XPath 表達(dá)式的節(jié)點(diǎn)列表。
- Select?Single?Node(String) : 選擇匹配 XPath 表達(dá)式的第一個 XmlNode。
- Write?Content?To(Xml?Writer) : 當(dāng)在派生類中被重寫時,該節(jié)點(diǎn)的所有子節(jié)點(diǎn)會保存到指定的 XmlWriter 中。
- Write?To(Xml?Writer) : 當(dāng)在派生類中被重寫時,將當(dāng)前節(jié)點(diǎn)保存到指定的 XmlWriter 中。
- Clone() : 創(chuàng)建此節(jié)點(diǎn)的副本。
- Clone?Node(Boolean) : 當(dāng)在派生類中被重寫時,創(chuàng)建該節(jié)點(diǎn)的副本
- Create?Navigator() : 創(chuàng)建 XPathNavigator 以瀏覽此對象。
2、XML文檔:XMLDocument
1、屬性:
- Document?Element : 獲取文檔的根 XmlElement。
- Document?Type : 獲取包含 DOCTYPE 聲明的節(jié)點(diǎn)。
- Preserve?Whitespace : 獲取或設(shè)置一個值,該值指示是否在元素內(nèi)容中保留空白區(qū)域。
- Schemas : 獲取或設(shè)置與此 XmlDocument 關(guān)聯(lián)的 XmlSchemaSet 對象。
- Xml?Resolver : 設(shè)置 XmlResolver 以用于解析外部資源。
2、方法:
- Get?Element?ById(String) : 獲取具有指定 ID 的 XmlElement。
- Get?Elements?ByTag?Name(String) : 返回一個 XmlNodeList,它包含與指定 Name 匹配的所有子代元素的列表。
- Import?Node(Xml?Node, Boolean) : 將節(jié)點(diǎn)從另一個文檔導(dǎo)入到當(dāng)前文檔。Load(Stream) 從指定的流加載 XML 文檔。
- Load(String) : 從指定的 URL 加載 XML 文檔。。
- Load?Xml(String) : 從指定的字符串加載 XML 文檔。
- Save(String) : 將 XML 文檔保存到指定的文件。 如果存在指定文件,則此方法會覆蓋它。
- Validate(Validation?Event?Handler) : 驗證 XmlDocument 是不是 Schemas 屬性中包含的 XML 架構(gòu)定義語言(XSD) 架構(gòu)。
- Read?Node(Xml?Reader) : 根據(jù) XmlReader 中的信息創(chuàng)建一個 XmlNode 對象。 讀取器必須定位在節(jié)點(diǎn)或?qū)傩陨稀?/li>
- Create?****(String) : 創(chuàng)建具有指定 Name 的 Xml***。
- Create?Navigator() : 創(chuàng)建一個用于導(dǎo)航此文檔的新 XPathNavigator 對象。
3、事件:
- Node?Changing、Node?Changed: 當(dāng)屬于該文檔的節(jié)點(diǎn)的 Value 將、已被更改時發(fā)生。
- Node?Inserting、Node?Inserted: 將屬于該文檔的節(jié)點(diǎn)將、已插入另一個節(jié)點(diǎn)時發(fā)生。
- Node?Removing、Node?Removed: 當(dāng)屬于該文檔的節(jié)點(diǎn)將、已從其父級中移除時發(fā)生。
3、XML元素:XmlElement
1、屬性:
- Has?Attributes : 獲取一個 boolean 值,該值指示當(dāng)前節(jié)點(diǎn)是否有任何屬性。
- Is?Empty : 獲取或設(shè)置元素的標(biāo)記格式。
- Schema?Info : 獲取作為架構(gòu)驗證的結(jié)果分配給此節(jié)點(diǎn)的后架構(gòu)驗證信息集。
2、方法:
- Get?Attribute(String) : 返回具有指定名稱的特性的值。
- Get?Attribute?Node(String) : 返回具有指定名稱的 XmlAttribute。
- Has?Attribute(String) : 確定當(dāng)前節(jié)點(diǎn)是否具有帶有指定名稱的特性。
- Get?Elements?ByTag?Name(String) : 返回一個 XmlNodeList,它包含與指定 Name 匹配的所有子代元素的列表。
- Remove?All?Attributes() : 從元素移除所有指定的特性。 不移除默認(rèn)特性。
- Remove?Attribute(String) : 按名稱移除特性。
- Remove?Attribute?At(Int32) : 從元素中移除具有指定索引的特性節(jié)點(diǎn)。 (如果移除的特性有一個默認(rèn)值,則立即予以替換)。
- Remove?Attribute?Node(String, String) : 移除由本地名稱和命名空間 URI 指定的 XmlAttribute。 (如果移除的特性有一個默認(rèn)值,則立即予以替換)
三、創(chuàng)建與查詢XML
需要添加的命名空間:
using System.Xml;
1、XmlDocument方式創(chuàng)建
XmlDocument xmldoc = new XmlDocument(); //加入XML的聲明段落, XmlDeclaration xmldecl; xmldecl = xmldoc.CreateXmlDeclaration ("1.0", "gb2312", null); xmldoc.AppendChild(xmldecl); //加入一個根元素 XmlElement xmlelem = xmldoc.CreateElement ("", "Employees", ""); xmldoc.AppendChild(xmlelem); //加入另外一個元素 for (int i = 1; i < 3; i++) { XmlNode root = xmldoc.SelectSingleNode("Employees");//查找 XmlElement xe1 = xmldoc.CreateElement("Node");//創(chuàng)建一個節(jié)點(diǎn) xe1.SetAttribute("genre", "李贊紅");//設(shè)置該節(jié)點(diǎn)genre屬性 xe1.SetAttribute("ISBN", "2-3631-4");//設(shè)置該節(jié)點(diǎn)ISBN屬性 XmlElement xesub1 = xmldoc.CreateElement("title"); xesub1.InnerText = "CS從入門到精通";//設(shè)置文本節(jié)點(diǎn) xe1.AppendChild(xesub1);//添加到節(jié)點(diǎn)中 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);//添加到節(jié)點(diǎn)中 } //保存創(chuàng)建好的XML文檔 xmldoc.Save("../../data.xml");
結(jié)果:生成了名為data.xml的文件,內(nèi)容如下,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> </Employees>
2、XmlTextWriter方式創(chuàng)建
string strFilename = "../../data1.xml"; XmlTextWriter xmlWriter = new XmlTextWriter(strFilename, Encoding.Default);// 創(chuàng)建一個xml文檔 xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Employees"); xmlWriter.WriteStartElement("Node"); xmlWriter.WriteAttributeString("genre", "李贊紅"); xmlWriter.WriteAttributeString("ISBN", "2-3631-4"); xmlWriter.WriteStartElement("title"); xmlWriter.WriteString("CS從入門到精通"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("author"); xmlWriter.WriteString("候捷"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("price"); xmlWriter.WriteString("58.3"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.Close();
結(jié)果:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> </Employees>
3、創(chuàng)建XML片段:XmlDocument.CreateDocumentFragment()
XmlDocument xmldoc = new XmlDocument(); XmlDocumentFragment docFrag = xmldoc.CreateDocumentFragment(); docFrag.InnerXml = "aa"; Console.Write(docFrag.InnerXml); XmlElement root = xmldoc.DocumentElement; root.AppendChild(docFrag);
4、加載已有的XML文件:XmlDocument.Load()
XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Server.MapPath("data.xml")); XmlElement root = xmldoc.DocumentElement;//獲取根元素 foreach (XmlNode node in root.ChildNodes) { if (node.Attributes["gere"].Value == "a") { foreach (XmlNode node1 in node.ChildNodes) { if (node1.Name == "author") { node1.InnerText = "aa";//修改文本 } } } }
5、查詢節(jié)點(diǎn):SelectNodes
string str = @" 200 認(rèn)證信息匹配 "; var xd = new System.Xml.XmlDocument(); xd.LoadXml(str);//xml加載xml字符串 XmlNamespaceManager nsManager = new XmlNamespaceManager(xd.NameTable);//創(chuàng)建一個命名空間管理器 nsManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");//添加字符串時,命名空間管理器將會原子化這些字符串。 nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); nsManager.AddNamespace("amon", "https://api.xiaoheer.com/"); var rowNoteList = xd.SelectNodes("http://amon:ErrorRes", nsManager);//查找節(jié)點(diǎn) Console.WriteLine(rowNoteList[0]);
返回:
<ErrorRes xmlns="https://api.xiaoheer.com/"> <Err_code>200</Err_code> <Err_content>認(rèn)證信息匹配</Err_content> </ErrorRes>
6、按照文本文件讀取xml:StreamReader
StreamReader myFile = new StreamReader("../../data.xml", System.Text.Encoding.Default);//注意System.Text.Encoding.Default string myString = myFile.ReadToEnd();//myString是讀出的字符串 myFile.Close(); Console.Write(myString);
四、添加一個結(jié)點(diǎn):AppendChild
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../data.xml"); XmlNode root = xmlDoc.SelectSingleNode("Employees");//查找 XmlElement xe1 = xmlDoc.CreateElement("Node");//創(chuàng)建一個節(jié)點(diǎn) xe1.SetAttribute("genre", "張三");//設(shè)置該節(jié)點(diǎn)genre屬性 xe1.SetAttribute("ISBN", "1-1111-1");//設(shè)置該節(jié)點(diǎn)ISBN屬性 XmlElement xesub1 = xmlDoc.CreateElement("title"); xesub1.InnerText = "C#入門幫助";//設(shè)置文本節(jié)點(diǎn) xe1.AppendChild(xesub1);//添加到節(jié)點(diǎn)中 XmlElement xesub2 = xmlDoc.CreateElement("author"); xesub2.InnerText = "高手"; xe1.AppendChild(xesub2); XmlElement xesub3 = xmlDoc.CreateElement("price"); xesub3.InnerText = "158.3"; xe1.AppendChild(xesub3); root.AppendChild(xe1);//添加到節(jié)點(diǎn)中 xmlDoc.Save("../../data.xml");
結(jié)果:在xml原有的內(nèi)容里添加了一個結(jié)點(diǎn),內(nèi)容如下,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="張三" ISBN="1-1111-1"> <title>C#入門幫助</title> <author>高手</author> <price>158.3</price> </Node> </Employees>
五、修改結(jié)點(diǎn)
1、修改節(jié)點(diǎn)的值(屬性和子結(jié)點(diǎn)):
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../data.xml"); XmlNodeList nodeList = xmlDoc.SelectSingleNode("Employees").ChildNodes;//獲取Employees節(jié)點(diǎn)的所有子節(jié)點(diǎn) foreach (XmlNode xn in nodeList)//遍歷所有子節(jié)點(diǎn) { XmlElement xe = (XmlElement)xn;//將子節(jié)點(diǎn)類型轉(zhuǎn)換為XmlElement類型 if (xe.GetAttribute("genre") == "張三")//如果genre屬性值為“張三” { xe.SetAttribute("genre", "update張三");//則修改該屬性為“update張三” XmlNodeList nls = xe.ChildNodes;//繼續(xù)獲取xe子節(jié)點(diǎn)的所有子節(jié)點(diǎn) foreach (XmlNode xn1 in nls)//遍歷 { XmlElement xe2 = (XmlElement)xn1;//轉(zhuǎn)換類型 if (xe2.Name == "author")//如果找到 { xe2.InnerText = "亞勝";//則修改 } } } } xmlDoc.Save("../../data.xml");//保存。
結(jié)果:將原來的所有結(jié)點(diǎn)的信息都修改了,xml的內(nèi)容如下,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="update張三" ISBN="1-1111-1"> <title>C#入門幫助</title> <author>亞勝</author> <price>158.3</price> </Node> </Employees>
2、修改結(jié)點(diǎn)(添加結(jié)點(diǎn)的屬性和添加結(jié)點(diǎn)的子結(jié)點(diǎn))
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../data.xml"); XmlNodeList nodeList = xmlDoc.SelectSingleNode("Employees").ChildNodes;//獲取Employees節(jié)點(diǎn)的所有子節(jié)點(diǎn) foreach (XmlNode xn in nodeList) { XmlElement xe = (XmlElement)xn; xe.SetAttribute("test", "111111");//添加屬性 XmlElement xesub = xmlDoc.CreateElement("flag"); xesub.InnerText = "1"; xe.AppendChild(xesub);//添加子節(jié)點(diǎn) } xmlDoc.Save("../../data.xml");
結(jié)果:每個結(jié)點(diǎn)的屬性都添加了一個,子結(jié)點(diǎn)也添加了一個,內(nèi)容如下,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4" test="111111"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="李贊紅" ISBN="2-3631-4" test="111111"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="update張三" ISBN="1-1111-1" test="111111"> <title>C#入門幫助</title> <author>亞勝</author> <price>158.3</price> <flag>1</flag> </Node> </Employees>
六、刪除結(jié)點(diǎn)
1、刪除節(jié)點(diǎn)中的某一個屬性:
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../data.xml"); XmlNodeList xnl = xmlDoc.SelectSingleNode("Employees").ChildNodes; foreach (XmlNode xn in xnl) { XmlElement xe = (XmlElement)xn; xe.RemoveAttribute("genre");//刪除genre屬性 XmlNodeList nls = xe.ChildNodes;//繼續(xù)獲取xe子節(jié)點(diǎn)的所有子節(jié)點(diǎn) foreach (XmlNode xn1 in nls)//遍歷 { XmlElement xe2 = (XmlElement)xn1;//轉(zhuǎn)換類型 if (xe2.Name == "flag")//如果找到 { xe.RemoveChild(xe2);//則刪除 } } } xmlDoc.Save("../../data.xml");
結(jié)果:刪除了結(jié)點(diǎn)的一個屬性和結(jié)點(diǎn)的一個子結(jié)點(diǎn),內(nèi)容如下,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node ISBN="2-3631-4" test="111111"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node ISBN="2-3631-4" test="111111"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node ISBN="1-1111-1" test="111111"> <title>C#入門幫助</title> <author>亞勝</author> <price>158.3</price> </Node> </Employees>
2、刪除結(jié)點(diǎn):
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../data.xml"); XmlNode root = xmlDoc.SelectSingleNode("Employees"); XmlNodeList xnl = xmlDoc.SelectSingleNode("Employees").ChildNodes; for (int i = 0; i < xnl.Count; i++) { XmlElement xe = (XmlElement)xnl.Item(i); if (xe.GetAttribute("genre") == "張三") { root.RemoveChild(xe); if (i < xnl.Count) i = i - 1; } } xmlDoc.Save("../../data.xml");
結(jié)果:刪除了符合條件的所有結(jié)點(diǎn),原來的內(nèi)容:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="張三" ISBN="1-1111-1"> <title>C#入門幫助</title> <author>高手</author> <price>158.3</price> </Node> <Node genre="張三" ISBN="1-1111-1"> <title>C#入門幫助</title> <author>高手</author> <price>158.3</price> </Node> </Employees>
刪除后的內(nèi)容:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李贊紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </Node> </Employees>
3、替換子元素
XmlElement elem=xmldoc.CreateElement("title"); elem.InnerText="XX"; root.ReplaceChild(elem,root.FirstChild);
到此這篇關(guān)于C#使用XmlDocument操作XML的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#12中的Primary?Constructors主構(gòu)造函數(shù)詳解
主構(gòu)造函數(shù)把參數(shù)添加到class與record的類聲明中就是主構(gòu)造函數(shù),這篇文章主要介紹了C#12中的Primary?Constructors 主構(gòu)造函數(shù),需要的朋友可以參考下2023-11-11C#?DataSet結(jié)合FlyTreeView實現(xiàn)顯示樹狀模型數(shù)據(jù)
NineRays.WebControls.FlyTreeView?是?9rays.net?推出的一款功能強(qiáng)大的樹狀模型數(shù)據(jù)顯示控件,本文主要介紹了如何使用其并結(jié)合?DataSet對象進(jìn)行數(shù)據(jù)顯示,感興趣的可以了解下2024-04-04