C#操作XML文檔(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)


XML文檔是一種通用的文檔,這種文檔既可以用.config作為后綴也可以用.xml作為后綴。XML文檔主要由元素節點和節點的屬性共同構成的。它有且僅有一個根節點,其他的節點全部都是根節點的子節點或者子子節點;每一個節點有開始就一定會有結束,不可能出現有開始無結束的節點,節點主要有兩種類型:有InnerText的<city>……</city>和沒有InnerText的<city……/>。在節點中含有屬性,一個節點可以含有多個屬性,每個屬性是由名字和值共同構成的。

在XML文檔中,節點、屬性都是區分大小寫的。對於某個節點的屬性,Name是不能重復的,即使在定義屬性的時候,定義了兩個name完全相同的屬性,添加到同一個節點上面,后面的屬性會把前面的屬性覆蓋,不會報語法錯誤;對於某個節點下面的子節點,則可以添加多個完全相同的子節點。

對XML文檔的操作的前提是:XML文檔已經存在,並且根節點已經存在。

一、添加節點和屬性

1、定義一個XML的操作對象:

XmlDocument doc = new XmlDocument();

2、加載一個XML文件:

doc.Load(@"D:\App.config");

指定的文件一定要存在,否則會報錯的。

3、獲取根節點:

XmlNode root = doc.DocumentElement;

4、定義一個屬性:

XmlAttribute ra = doc.CreateAttribute("Name");

5、給屬性的值賦值:

ra.Value = "zwj2";

6、將屬性添加到節點上面:

root.Attributes.Append(ra);

7、再定義一個節點為根節點的子節點:

XmlNode root1 = doc.CreateElement("table");

8、給節點賦文本值:

root1.InnerText = "sdf1";

9、給節點定義並添加屬性

10、將該節點添加到父節點上去:

root.AppendChild(root1);

11、保存XML文檔:

doc.Save(@"D:\App.config");

注意:可以對一個節點添加多個屬性,那么各個屬性會依次往后排;可以給根節點添加多個子節點,也可以對子節點再添加多個子節點。

二、查詢和修改節點和屬性

1、元素結點有Name屬性,就是<>里面的串,也有InnerText屬性(相當於文本結點),就是<></>之間的串:root.Nameroot.InnerText。這些屬性都是可以讀寫的。------------------------------XmlNode

2、屬性結點有Name,也有ValueproviderName="System.Data.SqlClient",前面為Name,后面為Value這些屬性既可讀也可寫。-----------------------------------------------------------XmlAttribute

3、每一個結點有子結點的集合,也有屬性的集合:root.ChildNodesroot.Attributes;集合都有count屬性。

4、集合都滿足索引:

對於屬性集合,屬性的name是不能重復的,所以索引可以是name字符串索引,那么name字符串要存在,否則返回的是一個null屬性對象,不會報錯;也可以是整數索引,那么此時的整數不能越界,否則是會報錯的;:root.Attributes["name"]root.Attributes[0],返回XmlAttribute。

對於子節點的集合,因為子節點可以完全相同,那么子節點的name肯定也可以相同,所以此時的索引只能是整數的,而不能是子節點name字符串,整數索引也不能越界,否則會報錯: root.ChildNodes[10],返回XmlNode。

三、幾個重要的函數

1XmlNode XmlDocument.SelectSingleNode(@"configuration/twoNode/dayStart")

這個函數是用一個聲明好的並且已經成功加載了某個配置文件的XmlDocument對象去調用SelectSingleNode函數;該函數的參數是配置文件中的從根節點名字開始一直往下最終到想要的節點的名字,整個名字路徑都不能出錯,注意是左斜杠;函數的返回值是第一次找到的XmlNode節點的對象,如果找不到就會返回null

操作如下xml

<?xmlversion="1.0"?>

<configuration>

  <twoNode>

  </twoNode>

  <twoNode>

    <dayStart>1</dayStart>

    <dayStart>2</dayStart>

    <dayStart>3</dayStart>

  </twoNode> 

</configuration>

如果執行該函數,那么將會找到節點:<dayStart>1</dayStart>

2XmlNodeList XmlDocument.SelectNodes (@"configuration/twoNode/dayStart")

這個函數是用一個聲明好的並且已經成功加載了某個配置文件的XmlDocument對象去調用SelectNodes函數;該函數的參數是配置文件中的從根節點名字開始一直往下最終到想要的節點的名字,整個名字路徑都不能出錯,注意是左斜杠;因為節點的名字是可能重復的,所以函數的返回值是找到的所有XmlNode節點對象的集合XmlNodeList,如果找不到就會返回null

XmlNodeList是集合,那么就有count屬性,可以直接對這個集合用[int index]來索引具體的對象,也可以用集合的Item(int index)函數來索引具體的對象,但是索引不能越界,否則會出錯,返回的是XmlNode。

操作如下xml

<?xmlversion="1.0"?>

<configuration>

  <twoNode>

    <dayStart>-1</dayStart>

    <dayStart>-2</dayStart>

    <dayStart>-3</dayStart>

  </twoNode>

  <twoNode>

    <dayStart>1</dayStart>

    <dayStart>2</dayStart>

    <dayStart>3</dayStart>

  </twoNode> 

</configuration>

如果執行該函數,那么將會找到節點集合:

    <dayStart>-1</dayStart>

    <dayStart>-2</dayStart>

<dayStart>-3</dayStart>

    <dayStart>1</dayStart>

    <dayStart>2</dayStart>

<dayStart>3</dayStart>

 

操作如下xml

<?xmlversion="1.0"?>

<configuration>

  <twoNode>

  </twoNode>

  <twoNode>

    <dayStart>1</dayStart>

    <dayStart>2</dayStart>

    <dayStart>3</dayStart>

  </twoNode> 

</configuration>

如果執行該函數,那么將會找到節點集合:

    <dayStart>1</dayStart>

    <dayStart>2</dayStart>

    <dayStart>3</dayStart>

 

注:轉載自csdn http://blog.csdn.net/zwj7612356/article/details/8183931

 

下面就開始進行實際操作吧!

.添加一個xml文件,名為book.xml ,內容如下:

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book Type="必修課" ISBN="7-111-19149-2">
    <title>數據結構</title>
    <author>嚴蔚敏</author>
    <price>30.00</price>
  </book>
  <book Type="必修課" ISBN="7-111-19149-3">
    <title>路由型與交換型互聯網基礎</title>
    <author>程慶梅</author>
    <price>27.00</price>
  </book>
  <book Type="必修課" ISBN="7-111-19149-4">
    <title>計算機硬件技術基礎</title>
    <author>李繼燦</author>
    <price>25.00</price>
  </book>
  <book Type="必修課" ISBN="7-111-19149-5">
    <title>軟件質量保證與管理</title>
    <author>朱少民</author>
    <price>39.00</price>
  </book>
  <book Type="必修課" ISBN="7-111-19149-6">
    <title>算法設計與分析</title>
    <author>王紅梅</author>
    <price>23.00</price>
  </book>
  <book Type="選修課" ISBN="7-111-19149-1">
    <title>計算機操作系統</title>
    <author>你猜</author>
    <price>28</price>
  </book>
</bookstore>

.添加一個web頁面,名為 XML_Operation.aspx,頁面內容如下:

一共4個按鈕,分別是button1、button2、button3、button4,然后是一個GridView1用來顯示數據

 

.添加一個BookModel.cs類用於讀取數據,內容如下:

 public class BookModel
    {
        //構造函數
        public BookModel(){}

        /// <summary>
        ///  所對應的課程類型
        /// </summary>
        public string BookType { get; set; }

        /// <summary>
        /// 書所對應的ISBN號
        /// </summary>
        public string BookISBN { get; set; }

        /// <summary>
        /// 書名
        /// </summary>
        public string BookName { get; set; }

        /// <summary>
        /// 作者
        /// </summary>
        public string BookAuthor { get; set; }

        /// <summary>
        /// 價格
        /// </summary>
        public string BookPrice { get; set; }
    }

 

.后台代碼如下:

1.添加命名空間 using System.Xml;

2.添加公共方法,用於操作當前XML

  1         /// <summary>
  2         /// XML操作公共方法
  3         /// </summary>
  4         /// <param name="oname">操作類型,create代表創建、delete代表刪除、update代表修改、select代表查詢</param>
  5         private void OperationXML(string oname) 
  6         {
  7             
  8             XmlDocument xmldoc = new XmlDocument();//xml操作文檔類
  9             //xmldoc.Load(@"D:\Practice\Test20150703\AboutXML\AboutXML\book.xml");
 10 
 11             XmlReaderSettings set = new XmlReaderSettings();
 12             set.IgnoreComments = true;//忽略文檔注釋
 13             XmlReader reader = XmlReader.Create(@"D:\Practice\Test20150703\AboutXML\AboutXML\book.xml", set);
 14             xmldoc.Load(reader);
 15             reader.Close();
 16             XmlNode node = xmldoc.SelectSingleNode("bookstore");
 17             XmlNodeList childs = node.ChildNodes;
 18             switch (oname) 
 19             {
 20                 case "create"://增加
 21                     #region
 22                     XmlElement xmlnew = xmldoc.CreateElement("book");
 23                     XmlAttribute xmlattri = xmldoc.CreateAttribute("Type");//添加類型
 24                     xmlattri.Value = "新類型";
 25                     xmlnew.SetAttributeNode(xmlattri);
 26                     XmlAttribute isbnatti = xmldoc.CreateAttribute("ISBN");//添加編號
 27                     xmlnew.SetAttributeNode(isbnatti);
 28                     isbnatti.Value = DateTime.Now.ToString("yyyymmddHHmmssfff");//注意,最后的f代表毫秒,可以取毫秒的前幾位數,比如毫秒123可以用ff取到12
 29                     node.AppendChild(xmlnew);//將新節點添加到根節點里面
 30 
 31                     XmlElement titlenew = xmldoc.CreateElement("title");
 32                     titlenew.InnerText = "newtitle";
 33                     xmlnew.AppendChild(titlenew);//在book字節點下面繼續添加子節點
 34                     XmlElement authornew = xmldoc.CreateElement("author");
 35                     authornew.InnerText = "newauthor";
 36                     xmlnew.AppendChild(authornew);//在book字節點下面繼續添加子節點
 37                     XmlElement pricenew = xmldoc.CreateElement("price");
 38                     pricenew.InnerText = "100k";
 39                     xmlnew.AppendChild(pricenew);//在book字節點下面繼續添加子節點
 40 
 41                     SaveXML(xmldoc,@"D:\Practice\Test20150703\AboutXML\AboutXML\book.xml");//保存並刷新
 42                     #endregion
 43                     break;
 44                 case "delete"://刪除
 45                     #region
 46                     //想要刪除某一個結點,直接找到其父結點,然后調用RemoveChild方法即可,現在關鍵的問題是如何找到這個結點,上面的SelectSingleNode可以傳入一個Xpath表,我們通過書的ISBN號來找到這本書所在的結點
 47                     string xmlPath = string.Format("/bookstore/book[@Type=\"{0}\" and @ISBN=\"{1}\"]", GridView1.Rows[GridView1.Rows.Count - 1].Cells[0].Text, GridView1.Rows[GridView1.Rows.Count - 1].Cells[1].Text);
 48                     XmlNode xmldelete = xmldoc.DocumentElement.SelectSingleNode(xmlPath);//"/bookstore/book[@ISBN=\"{0}\"]"是一個Xpath表達式,找到類型為所選那一行類型的那本書
 49                     if (xmldelete != null)
 50                     {
 51                         xmldelete.ParentNode.RemoveChild(xmldelete);
 52                     }
 53                     SaveXML(xmldoc,@"D:\Practice\Test20150703\AboutXML\AboutXML\book.xml");//保存並刷新
 54                     #endregion
 55                     break;
 56                 case "update"://修改
 57                     #region
 58                     //修改某條數據的話,首先也是用Xpath表達式找到所需要修改的那一個結點,然后如果是元素的話,就直接對這個元素賦值,如果是屬性的話,就用SetAttribute方法設置即可
 59                     
 60                     //方法1
 61                     string xmlpath = string.Format("/bookstore/book[@Type=\"{0}\"]", GridView1.Rows[GridView1.Rows.Count - 1].Cells[0].Text);
 62                     XmlNode updatenode = xmldoc.DocumentElement.SelectSingleNode(xmlpath);
 63                     updatenode.Attributes.GetNamedItem("Type").InnerText = "testtype";
 64                     if (updatenode.ChildNodes != null & updatenode.ChildNodes.Count > 0)
 65                     {
 66                         updatenode.ChildNodes.Item(0).InnerText = "testtitle";
 67                     }
 68 
 69                     //或方法2                   
 70                     //XmlElement updateattri = (XmlElement)xmldoc.DocumentElement.SelectSingleNode(xmlpath);
 71                     //updateattri.SetAttribute("Type", "修改類型");
 72                     //updateattri.GetElementsByTagName("title").Item(0).InnerText = "titleupdate";//注意這里只能用InnerText進行修改而不能用value進行修改
 73                     //updateattri.GetElementsByTagName("author").Item(0).InnerText = "authorupdate";
 74 
 75                     SaveXML(xmldoc,@"D:\Practice\Test20150703\AboutXML\AboutXML\book.xml");//保存並刷新
 76                     #endregion
 77                     break;
 78                 default:      //查詢
 79                     #region
 80      
 81                     List<BookModel> booklist = new List<BookModel>();//書本集合
 82                     foreach (XmlNode child in childs)
 83                     {
 84                         BookModel book = new BookModel();
 85                         XmlElement xe = (XmlElement)child;//將節點轉換為元素,便於得到節點的屬性值
 86                         book.BookType = xe.GetAttribute("Type");
 87                         book.BookISBN = xe.GetAttribute("ISBN");
 88 
 89                         XmlNodeList schild = child.ChildNodes;
 90                         if (schild != null && schild.Count > 0)
 91                         {
 92                             book.BookName = schild.Item(0).InnerText;
 93                             book.BookAuthor = schild.Item(1).InnerText;
 94                             book.BookPrice = schild.Item(2).InnerText;
 95                         }
 96                         else 
 97                         {
 98                             book.BookName = "";
 99                             book.BookAuthor = "";
100                             book.BookPrice = "";
101                         }
102                         booklist.Add(book);
103                     }
104                     GridView1.DataSource = booklist;
105                     GridView1.DataBind();
106                     #endregion
107                     break;
108             }
109         }
110 
111         //保存xml
112         private void SaveXML(XmlDocument xmldoc, string savePath) 
113         {
114             xmldoc.Save(savePath);//保存
115             OperationXML("select");//刷新
116         }
View Code

 另外,如果想獲取XML相對路徑,可以這樣做,首先引用命名空間using System.IO; 然后直接 stirng xmlPath = Server.MapPath("Gun.xml") 即可。

 

3.各個調用事件如下:

//查詢節點
        protected void Button1_Click(object sender, EventArgs e)
        {
            OperationXML("select");
        }

        //新增節點
        protected void Button2_Click(object sender, EventArgs e)
        {
            OperationXML("create");
        }

        //修改節點
        protected void Button3_Click(object sender, EventArgs e)
        {
            OperationXML("update");
        }

        //刪除節點
        protected void Button4_Click(object sender, EventArgs e)
        {
            OperationXML("delete");
        }

轉自:http://www.cnblogs.com/a1656344531/archive/2012/11/28/2792863.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM