標籤:
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(添加一個子節點) 摘錄