2013年9月17日 星期二

[轉貼] 用XmlDocument 進行XML操作


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
namespace Test_WebForm
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //《 使用範例 》
            //XmlFile.xml
            //<?xml version="1.0" encoding="utf-8"?>
            //<Root />
            string xml = Server.MapPath("XmlFile.xml");
            //插入元素
            XmlHelper.Insert(xml, "/Root", "Studio", "", "");
            //插入元素/屬性
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "歐陽逍遙");
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "信息大全");
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "逍遙軟體");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='逍遙軟體']", "Master", "", "歐陽逍遙");
            //插入屬性
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='歐陽逍遙']", "", "Url", "http://www.526net.com/");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='信息大全']", "", "Url", "http://www.jzxyp.com/");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='逍遙軟體']", "", "Url", "http://www.xiaoyaoking.com/");
            //修改元素值
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='逍遙軟體']/Master", "", "RedDust");
            //修改屬性值
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='逍遙軟體']", "Url", "http://blog.526net.com/");
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='逍遙軟體']", "Name", "PuTianCheng Studio");
            //讀取元素值
            Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site/Master", "") + "</div>");
            //讀取屬性值
            Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site", "Url") + "</div>");
            //讀取特定屬性值
            Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site[@Name='信息大全']", "Url") + "</div>");
            //刪除屬性
            XmlHelper.Delete(xml, "/Root/Studio/Site[@Name='歐陽逍遙']", "Url");
            //刪除元素
            XmlHelper.Delete(xml, "/Root/Studio", "");
        }
    }
    /// <summary>
    /// XmlHelper 的摘要說明
    /// </summary>
    public class XmlHelper
    {
        public XmlHelper()
        {
        }
        /// <summary>
        /// 讀取數據
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名,非空時返回該屬性值,否則返回串聯值</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用範例:
         * XmlHelper.Read(path, "/Node", "")
         * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute")
         ************************************************/
        public static string Read(string path, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }
        /// <summary>
        /// 插入數據
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="element">元素名,非空時插入新元素,否則在該元素中插入屬性</param>
        /// <param name="attribute">屬性名,非空時插入該元素屬性值,否則插入元素值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用範例:
         * XmlHelper.Insert(path, "/Node", "Element", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Element", "Attribute", "Value")
         * XmlHelper.Insert(path, "/Node", "", "Attribute", "Value")
         ************************************************/
        public static void Insert(string path, string node, string element, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
                doc.Save(path);
            }
            catch { }
        }
        /// <summary>
        /// 修改數據
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名,非空時修改該節點屬性值,否則修改節點值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用範例:
         * XmlHelper.Insert(path, "/Node", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
         ************************************************/
        public static void Update(string path, string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xe.InnerText = value;
                else
                    xe.SetAttribute(attribute, value);
                doc.Save(path);
            }
            catch { }
        }
        /// <summary>
        /// 刪除數據
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名,非空時刪除該節點屬性值,否則刪除節點值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用範例:
         * XmlHelper.Delete(path, "/Node", "")
         * XmlHelper.Delete(path, "/Node", "Attribute")
         ************************************************/
        public static void Delete(string path, string node, string attribute)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                doc.Save(path);
            }
            catch { }
        }
    }
}

******************************************************************************************
******************************************************************************************
******************************************************************************************
範例一:
books.xml

<?xml version="1.0" encoding="UTF-8"?>
<bookstore></bookstore>
******************************************************************************************
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test_WebForm._Default" %>
<html>
   <body>                 
      <form id="Form1"  runat="server">                       
      <asp:Button ID="Button1" runat="server" Text="插入節點" onclick="Button1_Click" /> 
      <asp:Button ID="Button2" runat="server" Text="修改節點" onclick="Button2_Click" /> 
      <asp:Button ID="Button3" runat="server" Text="刪除節點" onclick="Button3_Click" /> 
      </form>                            
   </body>                   
</html>
******************************************************************************************
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace Test_WebForm
{
    public partial class _Default : System.Web.UI.Page
    {
        XmlDocument xmlDoc = new XmlDocument();
        protected void Page_Load(object sender, EventArgs e)
        {
            xmlDoc.Load(Server.MapPath("/") + "bookstore.xml");
            if (!IsPostBack)
            {
                ReLoad();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //插入節點
            XmlNode root = xmlDoc.SelectSingleNode("bookstore");  //查找
            XmlElement xe1 = xmlDoc.CreateElement("book");        //創建一個節點
            xe1.SetAttribute("genre", "李贊紅");                  //設置該節點genre屬性
            xe1.SetAttribute("ISBN", "2-3631-4");                 //設置該節點ISBN屬性
            XmlElement xesub1 = xmlDoc.CreateElement("title");
            xesub1.InnerText = "CS從入門到精通";    //設置文本節點
            xe1.AppendChild(xesub1);                //添加到節點中
            XmlElement xesub2 = xmlDoc.CreateElement("author");
            xesub2.InnerText = "候捷";
            xe1.AppendChild(xesub2);
            XmlElement xesub3 = xmlDoc.CreateElement("price");
            xesub3.InnerText = "58.3";
            xe1.AppendChild(xesub3);
            root.AppendChild(xe1);    //添加到節點中
            xmlDoc.Save("bookstore.xml");
            ReLoad();
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            //修改節點
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;  //獲取bookstore節點的所有子節點
            foreach (XmlNode xn in nodeList)  //遍歷所有子節點
            {
                XmlElement xe = (XmlElement)xn;  //將子節點類型轉換為XmlElement類型
                if (xe.GetAttribute("genre") == "李贊紅")  //如果genre屬性值為「李贊紅」
                {
                    xe.SetAttribute("genre", "update李贊紅");  //則修改該屬性為「update李贊紅」
                    XmlNodeList nls = xe.ChildNodes;  //繼續獲取xe子節點的所有子節點
                    foreach (XmlNode xn1 in nls)  //遍歷
                    {
                        XmlElement xe2 = (XmlElement)xn1;  //轉換類型
                        if (xe2.Name == "author")  //如果找到
                        {
                            xe2.InnerText = "亞勝";  //則修改
                            break;  //找到退出來就可以了
                        }
                    }
                    break;
                }
            }
            xmlDoc.Save("bookstore.xml");
            ReLoad();
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            //刪除節點
            XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("genre") == "fantasy")
                {
                    xe.RemoveAttribute("genre");  //刪除genre屬性
                }
                else if (xe.GetAttribute("genre") == "update李贊紅")
                {
                    xe.RemoveAll();  //刪除該節點的全部內容
                }
            }
            xmlDoc.Save("bookstore.xml");
            ReLoad();
        }
        protected void ReLoad()
        {
            //顯示所有資料
            XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xnf in xnl)
            {
                XmlElement xe = (XmlElement)xnf;
                Console.WriteLine(xe.GetAttribute("genre"));  //顯示屬性值
                Console.WriteLine(xe.GetAttribute("ISBN"));
                XmlNodeList xnf1 = xe.ChildNodes;
                foreach (XmlNode xn2 in xnf1)
                {
                    Response.Write(xn2.InnerText + "<br>");  //顯示子節點點文本
                }
            }
        }
    }
}

******************************************************************************************
******************************************************************************************
******************************************************************************************
範例二:
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.Linq;
using System.Text;
using System.Xml;
namespace XML
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
              -------------------------------------------------
              這是一個用XmlDocument 進行XML操作的的例子,
              包含了查詢、增加、修改、刪除、保存的基本操作。
              較完整的描述了一個XML的整個操作流程。
              適合剛入門.net XML操作的朋友參考和學習。
              -------------------------------------------------
            */
            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);
                Console.ReadKey();
                //---  新建一本書完成 ----
                //---  下面對《哈利波特》做一些修改。 ----
                //---  查詢找《哈利波特》----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[name='哈利波特']");
                Console.Out.WriteLine("---  查找《哈利波特》 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                Console.ReadKey();
                //---  此時修改這本書的價格 -----
                theBook.GetElementsByTagName("price").Item(0).InnerText = "15";  //getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,GetElementsByTagName("price")相當於SelectNodes(".//price")。
                Console.Out.WriteLine("---  此時修改這本書的價格 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                Console.ReadKey();
                //---  另外還想加一個屬性id,值為B01 ----
                theBook.SetAttribute("id", "B01");
                Console.Out.WriteLine("---  另外還想加一個屬性id,值為B01 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                Console.ReadKey();
                //---  對《哈利波特》修改完成。 ----
                //---  要用id屬性刪除《三國演義》這本書  ----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B02']");
                Console.Out.WriteLine("---  要用id屬性刪除《三國演義》這本書 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                Console.ReadKey();
                theBook.ParentNode.RemoveChild(theBook);
                Console.Out.WriteLine("---  刪除後的XML ----");
                Console.Out.WriteLine(xmldoc.OuterXml);
                Console.ReadKey();
                //---  再將所有價格低於10的書刪除  ----
                XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
                Console.Out.WriteLine("---  再將所有價格低於10的書刪除  ---");
                Console.Out.WriteLine("---  符合條件的書有 " + someBooks.Count + "本。  ---");
                Console.ReadKey();
                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);
                Console.ReadKey();
                xmldoc.Save("books.xml");  //保存到books.xml
                Console.In.Read();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}

沒有留言:

張貼留言