1. 程式人生 > >C#操作XML的完整例子——XmlDocument篇

C#操作XML的完整例子——XmlDocument篇

{
                xmldoc.Load(
"Books.xml");
                root 
= xmldoc.DocumentElement;

                
//---  新建一本書開始 ----
                theBook = xmldoc.CreateElement("book");
                theElem 
= xmldoc.CreateElement("name");
                theElem.InnerText 
="新書";
                theBook.AppendChild(theElem);

                theElem 
= xmldoc.CreateElement("price");
                theElem.InnerText 
="20";
                theBook.AppendChild(theElem);

                theElem 
= xmldoc.CreateElement("memo");
                theElem.InnerText 
="新書更好看。";
                theBook.AppendChild(theElem);
                root.AppendChild(theBook);
                Console.Out.WriteLine(
"---  新建一本書開始 ----");
                Console.Out.WriteLine(root.OuterXml);
                
//---  新建一本書完成 ----

                
//---  下面對《哈里波特》做一些修改。 ----
                
//---  查詢找《哈里波特》----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[name='哈里波特']
");
                Console.Out.WriteLine(
"---  查詢《哈里波特》 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                
//---  此時修改這本書的價格 -----
                theBook.GetElementsByTagName("price").Item(0).InnerText ="15";//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,GetElementsByTagName("price")相當於SelectNodes(".//price")。
                Console.Out.WriteLine("---  此時修改這本書的價格 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                
//---  另外還想加一個屬性id,值為B01 ----
                theBook.SetAttribute("id""B01");
                Console.Out.WriteLine(
"---  另外還想加一個屬性id,值為B01 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                
//---  對《哈里波特》修改完成。 ----

                
//---  再將所有價格低於10的書刪除  ----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B02']");
                Console.Out.WriteLine(
"---  要用id屬性刪除《三國演義》這本書 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                theBook.ParentNode.RemoveChild(theBook);
                Console.Out.WriteLine(
"---  刪除後的XML ----");
                Console.Out.WriteLine(xmldoc.OuterXml);

                
//---  再將所有價格低於10的書刪除  ----
                XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
                Console.Out.WriteLine(
"---  再將所有價格低於10的書刪除  ---");
                Console.Out.WriteLine(
"---  符合條件的書有 "+ someBooks.Count +"本。  ---");

                
for (int i =0; i < someBooks.Count; i++)
                
{
                    someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
                }

                Console.Out.WriteLine(
"---  刪除後的XML ----");
                Console.Out.WriteLine(xmldoc.OuterXml);

                xmldoc.Save(
"books.xml");//儲存到books.xml

                Console.In.Read();
            }