這是一個用c#控制台程式下, 用XmlDocument 進行XML操作的的例子,包含了查詢、增加、修改、刪除、儲存的基本操作。較完整的描述了一個XML的整個操作流程。適合剛入門.net XML操作的朋友參考和學習。
假設有XML檔案:books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>哈裡傳輸速率</name>
<price>10</price>
<memo>這是一本很好看的書。</memo>
</book>
<book id="B02">
<name>三國演義</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水滸</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>紅樓</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
下面是為Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace TestXml
{
class Program
{
static void Main(string[] args)
{
XmlElement theBook = null, theElem = null, root = null;
XmlDocument xmldoc = new XmlDocument();
try
{
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();
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
}
}
}
From: http://hi.baidu.com/yanzuoguang/blog/item/7ba837cd56e9fd1c01e928d7.html