C#操作xml文件:使用XmlDocument 實現讀取和寫入

XML文件是一種常用的文件格式,例如WinForm裏面的app.config以及Web程序中的web.config文件,還有許多重要的場所都有它的身影。Xml是Internet環境中跨平臺的,依賴於內容的技術,是當前處理結構化文檔信息的有力工具。XML是一種簡單的數據存儲語言,使用一系列簡單的標記描述數據,而這些標記可以用方便的方式建立,雖然XML佔用的空間比二進制數據要佔用更多的空間,但XML極其簡單易於掌握和使用。微軟也提供了一系列類庫來倒幫助我們在應用程序中存儲XML文件。

    “在程序中訪問進而操作XML文件一般有兩種模型,分別是使用DOM(文檔對象模型)和流模型,使用DOM的好處在於它允許編輯和更新XML文檔,可以隨機訪問文檔中的數據,可以使用XPath查詢,但是,DOM的缺點在於它需要一次性的加載整個文檔到內存中,對於大型的文檔,這會造成資源問題。流模型很好的解決了這個問題,因爲它對XML文件的訪問採用的是流的概念,也就是說,任何時候在內存中只有當前節點,但它也有它的不足,它是隻讀的,僅向前的,不能在文檔中執行向後導航操作。”具體參見在Visual C#中使用XML指南之讀取XML

    下面我將介紹三種常用的讀取XML文件的方法。分別是 
   1: 使用 XmlDocument
   2: 使用 XmlTextReader

   3: 使用 Linq to Xml

下面我們使用XmlDocument:

1.讀取元素和屬性:

 XmlDocument doc = new XmlDocument();

            doc.Load("Customer2.xml");
            List<CustomerInfo> lists = new List<CustomerInfo>();

            XmlNodeList list = doc.SelectNodes("/Table/row");


            foreach (XmlNode item in list)
            {
                CustomerInfo cust = new CustomerInfo();
                cust.Version = item.Attributes["Version"].Value;
                cust.AppId = item.Attributes["AppId"].Value;
                cust.CustomerID = item["CustomerID"].InnerText;
                cust.CompanyName = item["CompanyName"].InnerText;
                cust.ContactName = item["ContactName"].InnerText;
                cust.ContactTitle = item["ContactTitle"].InnerText;
                cust.Address = item["Address"].InnerText;
                cust.City = item["City"].InnerText;
                cust.PostalCode = item["PostalCode"].InnerText;
                cust.Country = item["Country"].InnerText;
                cust.Phone = item["Phone"].InnerText;
                cust.Fax = item["Fax"].InnerText;
                lists.Add(cust);

            }

2.創建文檔-屬性和元素

XmlDocument doc = new XmlDocument();
            //    doc.Load("Customertest1.xml");
           
            XmlDeclaration xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(xmldecl, root);

             XmlElement ele = doc.CreateElement("Table");
             doc.AppendChild(ele);

             for (int i = 1; i < 10; i++)
             {
        
                 XmlElement row = doc.CreateElement("row");


                 row.SetAttribute("Version", "2.0");
                 row.SetAttribute("AppId", "111");

                 XmlElement custmonerId = doc.CreateElement("CustomerID");
                 custmonerId.InnerText = "程沐喆" + i.ToString();
                 row.AppendChild(custmonerId);

                 XmlElement custmonername = doc.CreateElement("CompanyName");
                 custmonername.InnerText = "Alfreds Futterkiste" + i.ToString();
                 row.AppendChild(custmonername);


                 XmlElement contactName = doc.CreateElement("ContactName");
                 contactName.InnerText = "Maria Anders" + i.ToString();
                 row.AppendChild(contactName);


                 XmlElement contactTitle = doc.CreateElement("ContactTitle");
                 contactTitle.InnerText = "Sales Representative" + i.ToString();
                 row.AppendChild(contactTitle);




                 XmlElement address = doc.CreateElement("Address");
                 address.InnerText = "Obere Str. 57" + i.ToString();
                 row.AppendChild(address);


                 XmlElement city = doc.CreateElement("City");
                 city.InnerText = "Berlin";
                 row.AppendChild(city);


                 XmlElement postalCode = doc.CreateElement("PostalCode");
                 custmonerId.InnerText = "12209";
                 row.AppendChild(postalCode);


                 XmlElement country = doc.CreateElement("Country");
                 country.InnerText = "Germany";
                 row.AppendChild(country);


                 XmlElement phone = doc.CreateElement("Phonw");
                 phone.InnerText = "030-0074321";
                 row.AppendChild(phone);


                 XmlElement fax = doc.CreateElement("Fax");
                 fax.InnerText = "030-0076545";
                 row.AppendChild(fax);


                 ele.AppendChild(row);
             }


             doc.Save("Customertest2.xml");


3.在讀取的同時進行修改,刪除,添加


添加:

 XmlDocument doc = new XmlDocument();
            doc.Load("Customertest.xml");
            XmlElement ele = doc.DocumentElement;
            for (int i = 0; i < 2; i++)
{

                XmlElement cust = doc.CreateElement("Customers");


               cust.SetAttribute("CustomerID","程沐喆"+i.ToString());
                cust.SetAttribute("CompanyName","程沐喆"+i.ToString());
                cust.SetAttribute("ContactName", "程沐喆" + i.ToString());
                cust.SetAttribute("ContactTitle", "程沐喆" + i.ToString());
                cust.SetAttribute("Address", "Obere Str .57"+i.ToString());
                cust.SetAttribute("City", "Berlin");
                cust.SetAttribute("PostalCode", "12209");
                cust.SetAttribute("Country", "Germany");
                cust.SetAttribute("Phone", "030-0074321");
                cust.SetAttribute("Fax", "030-0076545");

                ele.AppendChild(cust);
                
            }

            doc.Save("Customertest.xml");

修改:

XmlDocument doc = new XmlDocument();
            doc.Load("Customertest1.xml");

            XmlNode ele = doc.SelectSingleNode("descendant::row[CustomerID='ALFKI1']");
            ele["CompanyName"].InnerText = "程沐喆";

            doc.Save("Customertest1.xml");

刪除:

XmlDocument doc = new XmlDocument();
            doc.Load("Customertest1.xml");




            XmlNode ele = doc.SelectSingleNode("descendant::row[CustomerID='ALFKI1']");
            doc.DocumentElement.RemoveChild(ele);
            doc.Save("Customertest1.xml");




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章