1. 程式人生 > >VB.NET中操作xml檔案

VB.NET中操作xml檔案

已知有一個XML檔案(bookstore.xml)如下:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
  往<bookstore>節點中插入一個<book>節點: 

Dim xmlDoc As New XmlDocument()
xmlDoc.Load("bookstore.xml")
Dim root As XmlNode = xmlDoc.SelectSingleNode("bookstore") '查詢<bookstore> 
Dim xe1 As XmlElement = xmlDoc.CreateElement("book") '建立一個<book>節點 
xe1.SetAttribute("genre", "李贊紅") '設定該節點genre屬性 
xe1.SetAttribute("ISBN", "2-3631-4") '設定該節點ISBN屬性 
Dim xesub1 As XmlElement = xmlDoc.CreateElement("title")
xesub1.InnerText = "CS從入門到精通" '設定文字節點 
xe1.AppendChild(xesub1) '新增到<book>節點中 
Dim xesub2 As XmlElement = xmlDoc.CreateElement("author")
xesub2.InnerText = "候捷"
xe1.AppendChild(xesub2)
Dim xesub3 As XmlElement = xmlDoc.CreateElement("price")
xesub3.InnerText = "58.3"
xe1.AppendChild(xesub3)
root.AppendChild(xe1) '新增到<bookstore>節點中 
xmlDoc.Save("bookstore.xml")
  結果為: 
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="李贊紅" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore> 
  修改節點:將genre屬性值為“李贊紅“的節點的genre值改為“update李贊紅”,將該節點的子節點<author>的文字修改為“亞勝”。 
Dim nodeList As XmlNodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes '獲取bookstore節點的所有子節點 
Dim xn As XmlNode
For Each xn In nodeList '遍歷所有子節點 
Dim xe As XmlElement = CType(xn, XmlElement) '將子節點型別轉換為XmlElement型別 
If xe.GetAttribute("genre") = "李贊紅" Then '如果genre屬性值為“李贊紅” 
xe.SetAttribute("genre", "update李贊紅") '則修改該屬性為“update李贊紅” 
Dim nls As XmlNodeList = xe.ChildNodes '繼續獲取xe子節點的所有子節點 
Dim xn1 As XmlNode
For Each xn1 In nls '遍歷 
Dim xe2 As XmlElement = CType(xn1, XmlElement) '轉換型別 
If xe2.Name = "author" Then '如果找到 
xe2.InnerText = "亞勝" '則修改 
Exit ForEach '找到退出來就可以了 
End If
Next xn1
Exit ForEach
End If
Next xn
  顯示所有資料。 
Dim xn As XmlNode = xmlDoc.SelectSingleNode("bookstore")
Dim xnl As XmlNodeList = xn.ChildNodes
Dim xnf As XmlNode
For Each xnf In xnl
Dim xe As XmlElement = CType(xnf, XmlElement)
Console.WriteLine(xe.GetAttribute("genre")) '顯示屬性值 
Console.WriteLine(xe.GetAttribute("ISBN"))
Dim xnf1 As XmlNodeList = xe.ChildNodes
Dim xn2 As XmlNode
For Each xn2 In xnf1
Console.WriteLine(xn2.InnerText) '顯示子節點點文字 
Next xn2
Next xnf