C#操作XML方法:新增、修改和刪除節點與屬性


一 前言

先來了解下操作XML所涉及到的幾個類及之間的關系  如果大家發現少寫了一些常用的方法,麻煩在評論中指出,我一定會補上的!謝謝大家

* 1 XMLElement 主要是針對節點的一些屬性進行操作
* 2 XMLDocument 主要是針對節點的CUID操作
* 3 XMLNode 為抽象類,做為以上兩類的基類,提供一些操作節點的方法

清楚了以上的關系在操作XML時會更清晰一點

二 具體操作

以下會對Xml的結點與屬性做增 刪 改 查的操作也滿足了實際工作中的大部分情況 

先構造一棵XML樹如下,其中也涉及到了寫入xml文檔的操作

 1         public void CreatXmlTree(string xmlPath)
 2         {
 3             XElement xElement = new XElement(
 4                 new XElement("BookStore",
 5                     new XElement("Book",
 6                         new XElement("Name", "C#入門", new XAttribute("BookName", "C#")),
 7                         new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
 8                         new XElement("Adress", "上海"),
 9                         new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
10                         ),
11                     new XElement("Book",
12                         new XElement("Name", "WCF入門", new XAttribute("BookName", "WCF")),
13                         new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
14                         new XElement("Adress", "北京"),
15                         new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
16                         )
17                         )
18                 );
19 
20             //需要指定編碼格式,否則在讀取時會拋:根級別上的數據無效。 第 1 行 位置 1異常
21             XmlWriterSettings settings = new XmlWriterSettings();
22             settings.Encoding = new UTF8Encoding(false);
23             settings.Indent = true;
24             XmlWriter xw = XmlWriter.Create(xmlPath,settings);
25             xElement.Save(xw);
26             //寫入文件
27             xw.Flush();
28             xw.Close();
29         }

然后得到如下的XML樹

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <BookStore>
 3     <Book>
 4         <Name BookName="C#">C#入門</Name>
 5         <Author Name="Martin">Martin</Author>
 6         <Date>2013-10-11</Date>
 7         <Adress>上海</Adress>
 8         <Date>2013-10-11</Date>
 9     </Book>
10     <Book>
11         <Name BookName="WCF">WCF入門</Name>
12         <Author Name="Mary">Mary</Author>
13         <Adress>北京</Adress>
14         <Date>2013-10-11</Date>
15     </Book>
16 </BookStore>

以下操作都是對生成的XML樹進行操作

2.1 新增節點與屬性

新增節點NewBook並增加屬性Name="WPF"

 1         public void Create(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             
 6             var root = xmlDoc.DocumentElement;//取到根結點
 7             XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
 8             newNode.InnerText = "WPF";
 9 
10             //添加為根元素的第一層子結點
11             root.AppendChild(newNode);
12             xmlDoc.Save(xmlPath);
13         }

開篇有寫操作xml節點屬性主要用XmlElement對象所以取到結點后要轉類型 

 1         //屬性
 2         public void CreateAttribute(string xmlPath)
 3         {
 4             XmlDocument xmlDoc = new XmlDocument();
 5             xmlDoc.Load(xmlPath);
 6             var root = xmlDoc.DocumentElement;//取到根結點
 7             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             node.SetAttribute("Name", "WPF");
 9             xmlDoc.Save(xmlPath);
10 
11         }

效果如下

2.2 刪除節點與屬性

 1         public void Delete(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             var root = xmlDoc.DocumentElement;//取到根結點
 6 
 7             var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             root.RemoveChild(element);
 9             xmlDoc.Save(xmlPath);
10         }

刪除屬性

 1         public void DeleteAttribute(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 6             //移除指定屬性
 7             node.RemoveAttribute("Name");
 8             //移除當前節點所有屬性,不包括默認屬性
 9             //node.RemoveAllAttributes();
10             xmlDoc.Save(xmlPath);
11         }

2.3 修改節點與屬性

xml的節點默認是不允許修改的,本文也就不做處理了

  修改屬性代碼如下

1         public void ModifyAttribute(string xmlPath)
2         {
3             XmlDocument xmlDoc = new XmlDocument();
4             xmlDoc.Load(xmlPath);
5             XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
6             element.SetAttribute("Name", "Zhang");
7             xmlDoc.Save(xmlPath);
8         }

效果如下

2.4 獲取節點與屬性

 1         public void Select(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             //取根結點
 6             var root = xmlDoc.DocumentElement;//取到根結點
 7             //取指定的單個結點
 8             XmlNode oldChild = xmlDoc.SelectSingleNode("BookStore/NewBook");
 9             
10             //取指定的結點的集合
11             XmlNodeList nodes = xmlDoc.SelectNodes("BookStore/NewBook");
12 
13             //取到所有的xml結點
14             XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
15         }

屬性

1         public void SelectAttribute(string xmlPath)
2         {
3             XmlDocument xmlDoc = new XmlDocument();
4             xmlDoc.Load(xmlPath);
5             XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
6             string name = element.GetAttribute("Name");
7             Console.WriteLine(name);
8         }

三  linq to XML 操作

 Linq to Xml 也沒什么變化只操作對象改變了主要涉及的幾個對象如下   注:我並沒有用linq的語法去操作元素。

XDocument:用於創建一個XML實例文檔

XElement:用於一些節點與節點屬性的基本操作

以下是對Xml的 一些簡單的操作

3.1 新增節點與屬性

1         public void Create(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement xElement = xDoc.Element("BookStore");
5             xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
6             xDoc.Save(xmlPath);
7         }

屬性

 1         public void CreateAttribute(string xmlPath)
 2         {
 3             XDocument xDoc = XDocument.Load(xmlPath);
 4             IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
 5             foreach (var element in xElement)
 6             {
 7                 element.SetAttributeValue("Name", "Zery");
 8             }
 9             xDoc.Save(xmlPath);
10         }

3.2 刪除節點與屬性

1         public void Delete(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
5             element.Remove();
6             xDoc.Save(xmlPath);
7         }

屬性

1         public void DeleteAttribute(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             //不能跨級取節點
5             XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
6             element.Attribute("BookName").Remove();
7             xDoc.Save(xmlPath);
8         }

3.3 修改節點屬性

節點.net沒提供修改的方法本文也不做處理

修改屬性與新增實質是同一個方法

1         public void ModifyAttribute(string xmlPath)
2         {
3             XDocument xDoc = XDocument.Load(xmlPath);
4             XElement element = xDoc.Element("BookStore").Element("Book");
5             element.SetAttributeValue("BookName","ZeryTest");
6             xDoc.Save(xmlPath);
7         }

四 總結

把文章寫完時,又掃去了自己的一個盲區,雖然都是些簡單的操作,但在實際的開中,又何嘗不是由簡單到復雜呢。我覺得身為程序員就應該遇到自己的盲區時,立馬花時間去了解,不說要了解多深入,但至少基本的還是要知道,等到工作中真需時,只要稍微花點時間就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM