學習XML(添加一個子節點) 摘錄

來源:互聯網
上載者:User

標籤:

reference:http://blog.csdn.net/you_laner/article/details/1112129

 

 這裡介紹添加XML節點的方法。

       首先定義XML檔案:(bookstore.xml)

       <?xml version="1.0" encoding="utf-8"?>

       <bookstore>

              <book genre="fantasy" ISBN="2-9088-1">

                     <title>Oberon‘s Legacy</title>

                    <author>Corets,Eva</author>

                    <price>20.8</price>

              </book>

      </bookstore>

       OK,這就是有一個簡單節點的xml檔案,它有一個根節點bookstore,其子節點為book,其中book有兩個屬性genre 和ISBN,每個book節點又三個子節點title,author 和price。

       下面給這個xml檔案添加一個book子節點:

       1.引用XML名稱空間: Imports System.xml  

       2.定義一個讀取xml檔案的方法,暫且這麼說吧:

             Dim xmlDoc as New xmlDocument

             xmlDoc.Load("bookstore.xml")

        3.定義根結點,並找到根據節點名字找到根結點

            Dim root  as  XmlNode =xmlDoc.SelectSingleNode("bookstore")

         4.定義一級子節點,注意根結點與子節點的定義方式不同

           Dim xelement as XmlElement =xmlDoc.CreateElement("book")

           xelement.SetAttribute("genre","comedy")        //給一級子節點添加兩個屬性

           xelement.SetAttribute("ISBN","2-0875-3")

          5.定義二級子節點。節點的定義方式都是相同的,只是賦值的方式有所差別。這裡需要定義三個二階子節點

          Dim xesub1 as XmlElement =xmlDoc.CreateElement("title")

          xesub1.InnerText ="c#"       //給二級子節點賦值

          xelement.AppendChild(xesub1)        //將這個二階子節點添加給一級子節點

 

          Dim xesub2 as XmlElement =xmlDoc.CreateElement("author")

          xesub2.InnerText ="rubby"

          xelement.AppendChild(xesub2)

 

           Dim xesub3 as XmlElement =xmlDoc.CreateElement("price")

           xesub3.InnerText ="20.8"

           xelement.AppendChild(xesub3)

         6.將子節點添加到根節點中去,並儲存該xml檔案

           root.AppendChild(xelement)

           xmlDoc.Save("bookstore.xml")

       好了,我們再開啟xml檔案就會發現,已經新添加了一個book子節點了

學習XML(添加一個子節點) 摘錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.