C#操作XML增刪改查

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   os   ar   使用   java   

XML檔案是一種常用的檔案格式,不管是B/S還是C/S都隨處可見XML的身影。Xml是Internet環境中跨平台的,依賴於內容的技術,是當前處理結構化文檔資訊的有力工具。XML是一種簡單的資料存放區語言,使用一系列簡單的標記描述資料,而這些標記可以用方便的方式建立,雖然XML佔用的空間比位元據要佔用更多的空間,但XML極其簡單易於掌握和使用。微軟也提供了一系列類庫來倒協助我們在應用程式中儲存XML檔案。

    “在程式中訪問進而操作XML檔案一般有兩種模型,分別是使用DOM(文件物件模型)和流模型,使用DOM的好處在於它允許編輯和更新XML文檔,可以隨機訪問文檔中的資料,可以使用XPath查詢,但是,DOM的缺點在於它需要一次性的載入整個文檔到記憶體中,對於大型的文檔,這會造成資源問題。流模型很好的解決了這個問題,因為它對XML檔案的訪問採用的是流的概念,也就是說,任何時候在記憶體中只有當前節點,但它也有它的不足,它是唯讀,僅向前的,不能在文檔中執行向後導航操作。”

XML檔案建立

首先來看一個簡單的XML檔案:

<?xml version="1.0" encoding="UTF-8"?><Persons>  <Person id="1">    <Name>FlyElephant</Name>    <Age>24</Age>  </Person>  <Person id="2">    <Name>keso</Name>    <Age>25</Age>  </Person></Persons>

 這是最常見的Dom形式的XML檔案,建立的話也比較簡單,代碼如下:

     XmlDocument doc = new XmlDocument();            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);            doc.AppendChild(dec);            //根節點              XmlElement root = doc.CreateElement("Persons");            doc.AppendChild(root);            //根節點的添加獨立子節點              XmlElement person = doc.CreateElement("Person");            person.SetAttribute("id", "1");            person.AppendChild(getChildNode(doc, "Name", "FlyElephant"));            person.AppendChild(getChildNode(doc, "Age", "24"));            root.AppendChild(person);            //根節點的添加獨立子節點              person = doc.CreateElement("Person");            person.SetAttribute("id", "2");            person.AppendChild(getChildNode(doc, "Name", "keso"));            person.AppendChild(getChildNode(doc, "Age", "25"));            root.AppendChild(person);            doc.Save("person.xml");            Console.WriteLine("建立成功");
 XML檔案的讀取

C#中讀取XML有三種方式,XmlDocument,XmlTextReader,Linq to Xml,由於本人常用的是XmlDocument方法,其他的方法,有興趣的可以自己嘗試一下,看下查詢的實現:

   XmlDocument doc = new XmlDocument();            doc.Load("person.xml");    //載入Xml檔案              XmlElement root = doc.DocumentElement;   //擷取根節點              XmlNodeList personNodes = root.GetElementsByTagName("Person"); //擷取Person子節點集合              foreach (XmlNode node in personNodes)            {                string id = ((XmlElement)node).GetAttribute("id");   //擷取Name屬性值                  string name = ((XmlElement)node).GetElementsByTagName("Name")[0].InnerText;  //擷取Age子XmlElement集合                  string age = ((XmlElement)node).GetElementsByTagName("Age")[0].InnerText;                Console.WriteLine("編號:" + id + "姓名:" + name + "年齡:" + age);            }

  結果如下:

XML添加

XML存放的是資料結果跟類相似,如果業務需要往裡面動態添加資料,這個時候也需要個人控制一下,代碼如下:

           XmlDocument doc = new XmlDocument();            doc.Load("person.xml");            XmlElement root = doc.DocumentElement;            //根節點的添加獨立子節點              XmlElement person = doc.CreateElement("Person");            person.SetAttribute("id", "3");            person.AppendChild(getChildNode(doc, "Name", "Elephant"));            person.AppendChild(getChildNode(doc, "Age", "23"));            root.AppendChild(person);            doc.Save("person.xml");            Console.WriteLine("XML檔案中節點添加成功");

 這個時候XML檔案已經發生變化:

<?xml version="1.0" encoding="UTF-8"?><Persons>  <Person id="1">    <Name>FlyElephant修改</Name>    <Age>24</Age>  </Person>  <Person id="2">    <Name>keso</Name>    <Age>25</Age>  </Person>  <Person id="3">    <Name>Elephant</Name>    <Age>23</Age>  </Person></Persons>
 XML修改

修改其中的一個節點的話,最簡單的就是遍曆,遍曆的時候修改自己想要修改的元素:

   XmlDocument doc = new XmlDocument();            doc.Load("person.xml");    //載入Xml檔案              XmlElement root = doc.DocumentElement;   //擷取根節點              XmlNodeList personNodes = root.GetElementsByTagName("Person"); //擷取Person子節點集合            foreach (XmlNode node in personNodes)            {                XmlElement ele = (XmlElement)node;                if (ele.GetAttribute("id") == "3")                {                    XmlElement nameEle = (XmlElement)ele.GetElementsByTagName("Name")[0];                    nameEle.InnerText = nameEle.InnerText + "修改";                }            }            Console.WriteLine("節點修改成功");            doc.Save("person.xml");

  當然如果XML檔案中內容很多的話,這種方式就顯得的不是那麼的合理,可以修改一下一上代碼

            XmlElement selectEle = (XmlElement)root.SelectSingleNode("/Persons/Person[@id=‘1‘]");            XmlElement nameEle = (XmlElement)selectEle.GetElementsByTagName("Name")[0];            nameEle.InnerText = nameEle.InnerText + "修改";
XML刪除

經過上面的操作,刪除節點就很簡單的,代碼如下:

            XmlDocument doc = new XmlDocument();            doc.Load("person.xml");    //載入Xml檔案              XmlElement root = doc.DocumentElement;   //擷取根節點              XmlNodeList personNodes = root.GetElementsByTagName("Person"); //擷取Person子節點集合              XmlNode selectNode =root.SelectSingleNode("/Persons/Person[@id=‘1‘]");            root.RemoveChild(selectNode);            Console.WriteLine("節點刪除成功");            doc.Save("person.xml");

  周末看部落格的都是強人,大家周末愉快~

C#操作XML增刪改查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.